6

我正在尝试有条件地更改嵌套在无序列表中的元素的类。

当不使用ng-repeat创建列表时,我可以使用 jqlite 选择器.children()找到正确的元素并更改类。

但是,我正在使用ng-repeat创建列表,但不知道如何访问我想要的特定列表元素。.children()总是返回未定义。

这是我正在尝试做的事情的一个jsfiddle 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. 当用户单击特定元素时,该元素需要突出显示
  2. 当用户单击作为下一个元素的按钮时,将突出显示(该按钮不包含在 jsfiddle 中)

我考虑过将指令放在每个列表元素上,但唯一的问题是我不知道如何让它们都相互了解,所以一次只突出显示一个元素

4

1 回答 1

9

发生这种情况的原因是因为ng-repeat更改了模板 DOM,使得在指令编译时子级不存在。您需要在指令中设置一个$watchonelement.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

于 2013-05-25T18:15:47.910 回答