javascriptangularjsangularjs-directiveng-classangularjs-ng-class

how to get ng-class value in directive


I have some repeated 'li' elements, and some of them has 'active' class like this

<li ng-repeat="menuSubItem in menuItem.items" ng-class="{active: vm.currentMenuName == menuSubItem.name}" active-collapsible>

in the othe hand, I have a directive to add some classes depend on 'active' class, My directive is like this

directive('activeCollapsible', function() {
  return {
    restrict: 'A',
    link: function($scope, element, attrs) {

    }
  }
});

but I don't see 'active' class in 'element' argument. (I have already add jQuery before Angular.)

$(element).hasClass('active')

How Can I get 'active' class in my directive?


Solution

  • You could get the element has active class or not using $watch functino on scope, the function return in $watch first part will get evaluated everytime when digest cycle run & then you will get either true or false value on the basis of element.hasClasss('active')

    Directive

    directive('activeCollapsible', function() {
        return {
            restrict: 'A',
            link: function($scope, element, attrs) {
                $scope.$watch(function() {
                    return element.hasClass('active')
                }, function(newVal) {
                    if (newVal) //then it has active Class
                    //do something
                });
            };
        };
    });