是否可以“观察"属性的变化 [英] Is it possible to 'watch' attributes' changes

查看:23
本文介绍了是否可以“观察"属性的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以监视"指令上的 ui 更改?类似的东西:

Is it possible to "watch" for ui changes on the directive? something like that:

.directive('vValidation', function() {
    return function(scope, element, attrs) {
        element.$watch(function() {
            if (this.hasClass('someClass')) console.log('someClass added');
        });
    }
})

推荐答案

是的.如果在属性上使用插值,则可以使用 attr.$observe.

Yes. You can use attr.$observe if you use interpolation at the attribute.

但如果这不是内插属性,并且您希望它从应用程序中的其他地方更改(极不推荐,请阅读 常见陷阱),比你可以$watch一个函数返回:

But if this is not an interpolated attribute and you expect it to be changed from somewhere else in the application (what is extremely not recommended, read Common Pitfalls), than you can $watch a function return:

scope.$watch(function() {
    return element.attr('class'); 
}, function(newValue){
    // do stuff with newValue
});

无论如何,对您来说最好的方法可能是更改更改元素类的代码.哪个时刻发生了变化?

Anyway, its probably that the best approach for you would be change the code that changes the element class. Which moment does it get changed?

这篇关于是否可以“观察"属性的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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