whi*_*415 6 angularjs angularjs-directive ng-repeat
我试图条件性地改变嵌套在无序列表中的元素的类.
当不使用ng-repeat创建列表时,我可以使用jqlite选择器.children()来查找正确的元素并更改类.
但是我使用ng-repeat来创建列表,我无法弄清楚如何访问我想要的特定列表元素..children()总是返回undefined.
这是我想要做的事情的一个小问题 http://jsfiddle.net/whitehead1415/ENtTC/3/
app.directive('myDirective1', function () {
return {
restrict: 'A',
link: function ($scope, element, attrs, controller) {
//for some reason element.children()[0] is undefined
//why? what can I do about it?
angular.element(element.children()[0]).css('background', 'grey')
}
};
});
Run Code Online (Sandbox Code Playgroud)
我需要能够根据2件事改变课程
我想过将指令放在每个列表元素上,但唯一的问题是我不知道如何使它们彼此都知道,所以一次只突出显示一个元素
发生这种情况的原因是因为ng-repeat改变模板DOM的方式使得在指令编译时子节点不存在.您需要在指令中设置$watchon element.children(),以便在添加子项时通知指令并在此时应用CSS.在你的link函数中执行此操作(postLink当声明为指令方法时,这是一个函数):
$scope.$watch(element.children(),function(){
var children = element.children();
for(var i=0;i<children.length;i++){
if(children[i].nodeType !== 8){
angular.element(children[i]).css('background', 'grey');
}
}
});
Run Code Online (Sandbox Code Playgroud)
该$watch还需要检查并确保该nodeType不是注释(型8),因为ng-repeat插入的意见,如果你尝试应用CSS,这将抛出一个错误.
小提琴:这是working fiddle