directive $watch does not get invoked on class change

155 Views Asked by At

I have an angular app, using a left menu, with a show/hide menu bar, the action to show/hide on the left menu is a "data-action". I am using Smart Admin and the code is as below

<span class="minifyme" data-action="minifyMenu"> <i class="fa fa-arrow-circle-left hit"></i> </span>

When the data-action is fired, the body section class is changed or gets appeded a new class.

My requirement is to do something on the change of the class. I have a directive on the body to $watch for class.

The directive code surely gets invoked on load of the page, but it does not when the class is changed, i.e. when the data-action is performed.

(function () {
var app = angular.module("myApp");

var myDirective = [function () {
    return {
        restrict: "A",
        link: function (scope, element, attrs) {

            initialize();

            scope.$watch(function () {
             return element.attr('class');
        }, function (newValue) {
            if (element.hasClass('test')) {
                console.log('has class.');
            } else {
                console.log('classremoved.');
            }
        });

            function initialize() {

            };
        }
    };
}];

app.directive('myDirective', myDirective);

}());

How can I fix this issue.

1

There are 1 best solutions below

3
On

You need to do it in $apply() method as data-action is out of angular context.