使用AngularJS指令来更改ng-repeat元素的类

Use AngularJS directive to change classes of ng-repeat elements

本文关键字:ng-repeat 元素 AngularJS 指令 使用      更新时间:2023-09-26

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

当不使用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中)

我想把指令放在每个列表元素,但唯一的问题是,我不知道如何使他们都知道彼此,所以只有一个元素是突出显示在同一时间

发生这种情况的原因是因为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,将抛出错误。

小提琴:这是工作小提琴