angularjs – 使用angular指令来改变ng-repeat元素的类
发布时间:2020-12-17 10:16:45 所属栏目:安全 来源:网络整理
导读:我试图条件性地改变嵌套在无序列表中的元素的类. 当不使用ng-repeat创建列表时,我可以使用jqlite选择器.children()来查找正确的元素并更改类. 但是我使用ng-repeat来创建列表,我无法弄清楚如何访问我想要的特定列表元素. .children()总是返回undefined. 这是
我试图条件性地改变嵌套在无序列表中的元素的类.
当不使用ng-repeat创建列表时,我可以使用jqlite选择器.children()来查找正确的元素并更改类. 但是我使用ng-repeat来创建列表,我无法弄清楚如何访问我想要的特定列表元素. .children()总是返回undefined. 这是我想要做的事情的一个方面 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') } }; }); 我需要能够根据2件事改变课程 >当用户单击元素需要突出显示的特定元素时 我想过将指令放在每个列表元素上,但唯一的问题是我不知道如何使它们彼此都知道,所以一次只突出显示一个元素
发生这种情况的原因是因为ng-repeat改变了模板DOM,使得在指令编译时子节点不存在.您需要在指令中的element.children()上设置$watch,以便在添加子项时通知指令并在此时应用CSS.在链接函数中执行此操作(当声明为指令方法时,这是一个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'); } } }); $watch还需要检查并确保nodeType不是注释(类型8),因为ng-repeat插入注释,如果您尝试应用CSS,则会引发错误. 小提琴:这是working fiddle (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |