Javascript 如何在angular指令中获取当前dom元素
我是angularjs的新手,就像许多其他开发人员一样,我是jquery开发人员。现在我有一个关于指令的问题。 示例:如果我有这样的指令:Javascript 如何在angular指令中获取当前dom元素,javascript,angularjs,dom,angularjs-directive,angularjs-scope,Javascript,Angularjs,Dom,Angularjs Directive,Angularjs Scope,我是angularjs的新手,就像许多其他开发人员一样,我是jquery开发人员。现在我有一个关于指令的问题。 示例:如果我有这样的指令: app.directive('mydiv',function(){ return{ restrict:'AE', template:'<div><ul><li></li><li></li><li></li></ul><
app.directive('mydiv',function(){
return{
restrict:'AE',
template:'<div><ul><li></li><li></li><li></li></ul></div>', //of course in real case it will be use ng-repeat
link:function(scope,element,attr){
}
}
})
link: function (scope, element, attrs) { //when hover show the delete icon for each msg and apply highlight class to it.
element.find('li').hover(
function(){
$(this).addClass('highlight');
scope.deleteicon=true;
},
function(){
$(this).removeClass('highlight');
scope.deleteicon=false;
});
}
您可以将该元素作为链接函数本身的第一个参数(
element
参数)访问。如果将jquery与angular一起使用,并在angular之前加载jquery,那么元素`将被包装在jquery包装器中,即它将是一个jquery对象。如果不是angular,则使用称为jqlite的较轻的jquery子集。它只提供了最低限度的功能
有关详细信息,请参阅
您应该使用角度事件绑定并使用ng类
而不是添加/删除类,而不是手动绑定hover
事件。通过这种方式,您可以以有角度的方式执行操作,并且不需要通过scope.$apply()
指令的示例实现如下所示。使用角度内置指令本身有很多方法可以做到这一点
.directive('mydiv',function(){
return {
restrict:'AE',
scope:{items:"="}, //<-- data bound from parent scope via attribute
template:'<div><ul><li ng-mouseenter="toggleClass(true)" ng-mouseleave="toggleClass(false)" ng-class="{'highlight': action.deleteicon}" ng-repeat="item in items">{{item.name}}</li></ul></div>', //of course in real case it will be use ng-repeat
link:function(scope,element,attr){
scope.action = {deleteicon :true};
scope.toggleClass = function(show){
scope.action.deleteicon = show;
}
}
}
});
指令('mydiv',函数(){
返回{
限制:'AE',
范围:{items:“=”},//好吧,您使用了悬停
,但是,您可以使用
例如:
<li ng-mouseover="high = true" ng-class="{'highlight':high}">Content</li>
内容
标记:
<div class="row" ng-app="myapp" ng-controller="myctrl">
<div class="col-lg-3 col-lg-push-3">
<ul class="list-group">
<li class="list-group-item" ng-init="myclass='hide'" ng-repeat="item in items"
ng-mouseenter="myclass = 'show'" ng-mouseleave="myclass='hide'">
<span>{{item}}</span>
<span ng-class="'pull-right glyphicon glyphicon-edit '+myclass"></span>
</li>
</ul>
</div>
</div>
在您的链接函数中,注入了名为“element”的参数,该参数将是一个jqLite元素。您是否也需要某种鼠标退出功能?谢谢您提供的信息!但是如果我需要对每个
angular.module('myapp', [])
.controller('myctrl', function ($scope) {
$scope.items = ['abc', 'xyz', 'klm'];
});