ng-class 不会删除在 angular 被引导之前存在的类 [英] ng-class does not remove a class that was there before angular was bootstrapped

查看:19
本文介绍了ng-class 不会删除在 angular 被引导之前存在的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

还不到 72 小时就可以加快 angular 的速度.用了一段时间的淘汰赛,我不得不说它很有趣.我现在的问题与 ng-class 有关.

假设我有以下内容:

当 angular 引导时,它不会删除之前在那里呈现的 myClass 属性.我早就预料到了,因为这就是 ko 的 css 绑定所做的.如果 angular 是将它放在那里的人,那么似乎 angular 只会删除该类.

那么,有没有通用的解决方法呢?除了创建自定义指令?

解决方案

由于您仅将 Angular 用于表单,并且在 Angular 引导之前需要一个类在表单中的元素上处于活动状态,因此看起来可能是一个指令最好的方法.

一旦指令被 Angular 链接(这几乎与 ngClass 启动时相同),以下指令将从其所在的元素中删除指定的类:

.directive('removeClass', function(){返回 {限制:'A',链接:功能(范围,元素,属性){element.removeClass(attrs.removeClass);}};});

像这样使用:

<div class="oldClass" remove-class="oldClass" ng-class="{newClass: true}">stuff</div>

演示小提琴

Still under 72 hours coming up to speed with angular. Having used knockout for a while, I have to say it's interesting. My question right now has to do with ng-class.

Say I have the following:

<div class="myClass" ng-class="{myClass: false}">

When angular bootstraps, it does not remove the myClass attribute that was rendered there before. I had expected it to, since that's what ko's css binding does. It seems that angular only removes the class if angular was the one who put it there.

So, is there a common workaround for this? Other than creating a custom directive?

解决方案

Since you're only using Angular for the form and need a class to be active on elements within the form prior to Angular bootstraping it looks like a directive may be the best way to go.

The following directive will remove the specified class from the element its on once the directive is linked in by Angular (which is almost the same point when ngClass will kick in):

.directive('removeClass', function(){
    return {
        restrict: 'A',
        link: function(scope,element, attrs){
            element.removeClass(attrs.removeClass);
        }
    };
});

Used like so:

<div class="oldClass" remove-class="oldClass" ng-class="{newClass: true}">stuff</div>

demo fiddle

这篇关于ng-class 不会删除在 angular 被引导之前存在的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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