【问题标题】:Use AngularJS directive to change classes of ng-repeat elements使用 AngularJS 指令更改 ng-repeat 元素的类
【发布时间】:2013-05-25 16:16:24
【问题描述】:

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

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

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

这是我正在尝试做的一个 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 中)

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

【问题讨论】:

    标签: javascript html angularjs angularjs-directive angularjs-ng-repeat


    【解决方案1】:

    发生这种情况的原因是因为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 插入了 cmets,如果您尝试应用 CSS,则会引发错误。

    小提琴:这里是 working fiddle

    【讨论】:

    • 感谢这项工作!角度邮件列表中的某个人告诉我同样的事情。
    猜你喜欢
    • 1970-01-01
    • 2013-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    相关资源
    最近更新 更多