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

标签 javascript jquery angularjs

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

     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/

相关文章:

javascript - 从嵌套 $.get 返回值

javascript - 在 AngularJS 中声明工厂/服务最简洁的方法是什么?

javascript - NgRoute 在 jsfiddle 中不起作用

javascript - Firefox 中的 onKeyPress 文本框不起作用

javascript - 数据表无法响应作为示例

jquery - 无法通过 jQuery 禁用文本字段的 onclick/onblur 值

angularjs - Angular ui-router 完成条件 View

javascript - 使用 Jasmine 测试 Angular Controller 的 promise

javascript - 如何将字符串转换为真正的二进制表示形式(UTF-8 或当前使用的任何格式)?

javascript - 如何用一个字符填充整个div