使用角度指令来改变纳克重复元素的类 [英] use angular directive to change classes of ng-repeat elements

查看:83
本文介绍了使用角度指令来改变纳克重复元素的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图conditionaly修改类嵌套在一个无序列表中的元素。

I am trying to conditionaly change the class of an element that is nested in an unordered list.

在不使用NG-重复创建列表,我可以用jqlite选择。孩子()找到正确的元素,并更改类。

When not using ng-repeat to create the list I can use the jqlite selector .children() to find the correct element and change the class.

不过我用的NG-重复创建列表,我无法弄清楚如何获得我想要的具体名单元素。 。孩子()总是返回undefined。

However I am using ng-repeat to create the list and I can't figure out how to access the specific list element that I want. .children() always returns undefined.

这里是什么我试图做的jsfiddle
http://jsfiddle.net/whitehead1415/ENtTC/3/

here is a jsfiddle of what I am trying to do 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东西能够改变类

I need to be able to change the class based on 2 things


  1. ,当用户点击该元件需要以突出显示特定元件上

  2. 时(不包括在的jsfiddle该按钮)上的一个按钮,它是下一个元素将被高亮显示用户点击

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

I thought about putting the directive on each list element, but the only problem is that I don't know how to make them all aware of each other so only one element is highlighted at a time

推荐答案

发生这种情况的原因是因为 NG-重复以这样的方式改变模板DOM孩子们在该指令编译时间不存在。您需要设置一个 $观看 element.children()中的指令,使该指令将被通知时,孩子们被添加,并在该时间应用的CSS。在你的链接做到这一点功能(这是作为指令的方法声明时, postLink 功能):

The reason this happens is because ng-repeat alters the template DOM in such a way that the children do not exist at the time the directive compiles. You need to set a $watch on element.children() in the directive so that the directive will be notified when the children are added and apply the CSS at that time. Do this in your link function (which is a postLink function when declared as a directive method):

$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');
        }
    }
});

$腕表还需要检查并确保该节点类型不是注释(类型 8 ),因为 NG-重复插入注释,如果您尝试应用CSS,这将抛出一个错误。

The $watch also needs to check and make sure that the nodeType is not a comment (type 8) because ng-repeat inserts comments, which will throw an error if you try to apply CSS.

小提琴:这是<大骨节病> 工作拨弄

Fiddle: Here is the working fiddle

这篇关于使用角度指令来改变纳克重复元素的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆