Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
691 views
in Technique[技术] by (71.8m points)

angularjs - Is it possible to 'watch' attributes' changes

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');
        });
    }
})
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...