使用angular指令来改变ng-repeat元素的类

时间:2013-05-25 16:16:25

标签: 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')
        }
    };
});

我需要能够根据2件事改变课程

  1. 当用户点击元素需要突出显示的特定元素时
  2. 当用户点击按钮时,下一个元素将突出显示(该按钮不包含在jsfiddle中)
  3. 我考虑过将指令放在每个列表元素上,但唯一的问题是我不知道如何使它们彼此都知道,所以一次只突出显示一个元素

1 个答案:

答案 0 :(得分:9)

发生这种情况的原因是因为ng-repeat改变了模板DOM,使得在指令编译时子节点不存在。您需要在指令中的$watch上设置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');
        }
    }
});

$watch还需要检查并确保nodeType不是注释(类型8),因为ng-repeat会插入注释,如果发出错误,则会引发错误你试着申请CSS。

小提琴:这是 working fiddle