Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
        });
    }
})
like image 838
iLemming Avatar asked Apr 09 '13 19:04

iLemming


People also ask

What is$ watch in Angular?

The angular JS $watch function is used to watch the scope object. The $watch keep an eye on the variable and as the value of the variable changes the angular JS $what runs a function. This function takes two arguments one is the new value and another parameter is the old value.

What is the use of$ watch in AngularJS?

$watch() function is used to watch the changes of variables in $scope object. Generally the $watch() function will create internally in Angularjs to handle variable changes in application.


3 Answers

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?

like image 187
Caio Cunha Avatar answered Oct 17 '22 04:10

Caio Cunha


attrs.$observe('class', function(val){});
like image 29
Ketan Avatar answered Oct 17 '22 02:10

Ketan


You can also watch variable in the controller.

This code automatically hides notification bar after some other module displays the feedback message.

HTML:

<notification-bar
    data-showbar='vm.notification.show'>
        <p> {{ vm.notification.message }} </p>
</notification-bar>

DIRECTIVE:

var directive = {
    restrict: 'E',
    replace: true,
    transclude: true,
    scope: {
        showbar: '=showbar',
    },
    templateUrl: '/app/views/partials/notification.html',
    controller: function ($scope, $element, $attrs) {

        $scope.$watch('showbar', function (newValue, oldValue) {
            //console.log('showbar changed:', newValue);
            hide_element();
        }, true);

        function hide_element() {
            $timeout(function () {
                $scope.showbar = false;
            }, 3000);
        }
    }
};

DIRECTIVE TEMPLATE:

<div class="notification-bar" data-ng-show="showbar"><div>
    <div class="menucloud-notification-content"></div>
like image 2
Marcin Rapacz Avatar answered Oct 17 '22 04:10

Marcin Rapacz