Angular class 更改指令不起作用

Angular class change directive doesn't work

我想添加一个指令,该指令将在元素 class 更改时执行某些操作。

我的指令是:

(function (angular) {

angular.module('myApp')
    .directive('myClassWatch', myClassWatch);

function myClassWatch() {
    return {
        restrict: 'A',
        link: function (scope, element, attrs, controller) {
            scope.$watch(function () {
                return element.attr('class');
            }, function (newValue, oldValue) {
                debugger;
                if(oldValue !== newValue)
                    console.log('class changed from ' + oldValue + ' to ' + newValue);
            });
        }
    }
}
})(angular);

html是:

<div class="top-icons-item popup-container popup-link-container" my-class-watch>

</div>

我在其他地方做了一些操作,在我的 div 元素中切换 class "open" - 它在 html 中可见 - 但从未调用调试器(当然也没有控制台日志)。我可以看到 link 函数在页面加载时被调用并且调试器也停止了,但这只是在页面加载时而不是之后当我实际执行添加另一个 class.

的操作时

我已经阅读过这里发布的几篇文章,包括 Directive : $observe, class attribute change caught only once,但我不明白为什么我没有得到相同的结果。我该怎么做才能尝试检查为什么会发生这种情况?

更新:class 更改不是在控制器中而是在旧的 jquery 手表代码中使用 jQuery 进行的。这可能是原因吗?如果 angular 没有通过 angular 代码完成更改,那么 angular 会不知道 class 更改吗?

将您的 jQuery 代码包装成 $apply

这类似于您在 angular 上下文 (jquery ajax, setTimeout, etc) 之外对 $scope 进行更改。使用 $apply 让 angular 知道所做的更改。

    angular.element(document.getElementById('app')).injector().invoke(['$compile', '$rootScope', function($compile, $rootScope) {
       $rootScope.$apply(function() {
           //your jquery code goes here...
           var a = document.getElementById('abc');
           angular.element(a).addClass('hello');
       });
    }]);