Question

I have a UI.Bootstrap drowndown:

<li class="dropdown hello" id="contentMenu" watch-content>
          <a class="dropdown-toggle" >
            Content options
          </a>
          <ul class="dropdown-menu" >
            <li ng-repeat="option in options">
              <a><input type="checkbox" checklist-model="contentChoices"  checklist-value="option.id" ng-click="$event.stopPropagation()"> {{option.slug}} </a>
            </li>
          </ul>
        </li>

when this is clicked, it adds a class of open to the li.dropdown.hello

I am trying to watch for when the class open is added but it's not working.

.directive('watchContent', function ($window) {
return {
    restrict: 'A',
    link: function (scope, elem, attrs) {

    //     console.log(attrs.class)


        // attrs.$observe("class", function(value){
        //     console.log('change !');
        //     if(value.indexOf("open") > -1){
        //         alert("yes")
        //     }
        // })
    //     scope.$watch(function() {return attrs.class; }, function(newValue, oldValue, scope){
    //         console.log('change !');
    //         console.log(newValue)
    //         console.log(oldValue)
    //         console.log(scope)
    //         console.log(attrs.class)
    //         // debugger;
    //         if (elem.hasClass('open')) {
    //           console.log('YEs')
    //         } else {
    //           console.log('no')
    //         }
    //     });
      scope.$watch(function () {
          return elem[0].className;
      }, function (newValue, oldValue) {
          if (newValue === oldValue) { return; }
          alert(newValue);
      });
      scope.$apply()
    }
};
})
Was it helpful?

Solution

Without looking too deep into why, it is a fact that attrs does not handle the class attribute as expected.

You can watch the elements className instead:

scope.$watch(function () {
    return elem[0].className;
}, function (newValue, oldValue) {
    if (newValue === oldValue) { return; }
    alert(newValue);
});

See, also, this short demo.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top