Directive: $ observe, changing a class attribute is caught only once

I have a directive that changes the style of the div, and I would like it to be notified $ we observe every time the class of the element changes. The problem is that this happens when creating the directive, but not after. Here is the code and fiddle

<div ng-app="testObserve">
    <div ng-controller="Ctrl2"> 
        <span class="rouge" ng-click="toggleClass()" my-test>Coucou</span>
    </div>
</div>

angular.module('testObserve', [])
    .controller('Ctrl2', function ($scope) {})
    .directive('myTest', function () {

    function link(scope, element, attrs) {

        scope.toggleClass = function () {
            if (element.hasClass('rouge')) {
                element.removeClass('rouge');
            } else {
                element.addClass('rouge');
            }
            console.log( 'I become ' + element[0].outerHTML );
        };

        attrs.$observe('class', function (val) {
            console.log('class has changed' + val);
            debugger;
        });
    }

    return {
        link: link
    };
});

Is this normal behavior?


Well, I found it should be an ng class instead of a class in both html and js code (it is contained in the documentation).

Fixed js here .

So, I am changing the question a bit: if another js is changing the class but not the ng class, how can I notice this?


@koolunix ( unix is ​​kool:)) , js angular, boot wrap > w500 > -, .

, angular, ng-. , "" .

, , .

, ui-bootstrap , .

!

+3
1

$observe , .

:

<span class="{{something}}">Hello</span>

$watch , :

scope.$watch(function() {
  return element.attr('class');
}, function(newValue, oldValue) {
  if (newValue !== oldValue) { // Values will be equal on initialization
    console.log('class has changed to: ' + newValue);
  }
});

: http://plnkr.co/edit/SImhYTkN11eAECC8gDXm?p=preview

+5

All Articles