2013-05-25 30 views
6

我试图conditionally改变嵌套在无序列表中的元素的类。使用angular指令来改变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') 
     } 
    }; 
}); 

我需要基于两件事情

  1. 能够改变类的jsfiddle当在特定的用户点击元素需要突出显示
  2. 当用户点击一个按钮时,下一个元素将被突出显示(该按钮不包含在jsfiddle中)

我想过把指令每个列表元素,但唯一的问题是,我不知道如何让他们都知道彼此只有一个元素的同时强调了

回答

9

的发生这种情况的原因是因为ng-repeat改变了模板DOM,使得在指令编译时孩子不存在。您需要在指令中的element.children()上设置$watch,以便在添加子项并在当时应用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'); 
     } 
    } 
}); 

$watch还需要检查并确保该nodeType不是注释(类型8),因为ng-repeat刀片注释,如果您尝试应用CSS,则会引发错误。

小提琴:这里是working fiddle

+1

感谢这个作品!在一个角色邮件列表上的人告诉我同样的事情。 – whitehead1415