gpt4 book ai didi

javascript - Angular js 从指令触发 ng-class 切换

转载 作者:行者123 更新时间:2023-12-03 11:51:56 25 4
gpt4 key购买 nike

我有一个指令,当达到条件时会触发该指令来隐藏元素。

     var hideElement = function(){
el = element.find('.myelement');
$(el).addClass('hideme');
};

然后在条件下触发 hideElement 函数

 if(j >= count){
hideElement ();
}

如何在部分上重构它以更改 ng 类?

<div 
data-directivename
data-increment="increment"
data-count="count"
ng-class="{'timetohide': hide}"
>
<div class="myelement"></div>
</div>

最佳答案

只需使用范围变量:

var hideElement = function(){
scope.hide = true;
};

然后,您的 ng-class="{'timetohide': hide}" 将正常工作 - 当 时,该元素将获得 timetohide 类scope.hide 是真的。

<小时/>

更新

由于您在指令中使用隔离作用域,因此实际上需要修改父作用域变量,因为这是 ng 类正在监视的内容,因此上面的代码应该是:

var hideElement = function(){
scope.$parent.hide = true;
};

在这里查看:http://plnkr.co/edit/dXSi5hH4FEVQuDS9uMOl?p=preview (我们所有评论后的版本)

解释来自:http://www.undefinednull.com/2014/02/11/mastering-the-scope-of-a-directive-in-angularjs/

Scope : { } ( Directive gets a new isolated scope )

This is the most interesting section. Till now, we saw two situations for directive scope creation. In the third type, we are going to set scope property in DDO to an Object literal. When an object literal is passed to the scope property, things are bit different. This time, there will be a new scope created for the directive, but it will not be inherited from the parent scope. This new scope also known as Isolated scope because it is completely detached from its parent scope.

有道理。

关于javascript - Angular js 从指令触发 ng-class 切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25797186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com