我是 angularjs 新手,我无法解决这个问题。
指令
app.directive('rating', [function () {
return {
restrict: 'E',
scope: {
maxStars: '=',
},
link: function (scope, iElement, iAttrs) {
scope.stars = [];
for(var i=0;i<scope.maxStars;i++) {
scope.stars.push(i);
}
iElement.bind('mouseenter', function(event) {
scope.$apply(function(){
angular.forEach(iElement.children(),function(div){
angular.forEach(div.children,function(span){
span.addClass('rating-star-enabled'); //error addClass is not a function
});
});
});
});
},
templateUrl:'rating/rating.html'
};
}]);
指令模板
<div class="review-star">
<span class="glyphicon glyphicon-record" ng-repeat="star in stars"></span>
</div>
指令
<rating max-stars="5"></rating>
我收到错误 addClass 不起作用。它不仅仅适用于 addClass,如果我尝试任何其他函数,它会显示相同的错误。如果我将其登录到控制台,我可以看到它打印所有标签。所以它可以正确访问元素。我做错了什么?
最佳答案
当您对 iElement.children()
使用 angular.forEach()
时,您正在迭代原始 DOM 元素的数组(这就是为什么您需要使用div.children
而不是内部 angular.forEach()
中的 div.children()
)。您需要将 span
(也是原始 DOM 元素)转换为 jqLite 对象,然后才能调用 addClass()
...
scope.$apply(function(){
angular.forEach(iElement.children(),function(div){
angular.forEach(div.children,function(span){
angular.element(span).addClass('rating-star-enabled');
});
});
});
关于javascript - Angularjs - 如何将函数分配给指令中的嵌套元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24837084/