Search code examples
angularjsng-class

angularjs ng-class in nested directive


Tried so many different ways and still can't figure this. I have a menu with ng-class="{menuVisibleAnimation: menuOpen}" in a template in a nested directive. When I click on the button in the parent directive I want to change the value of menuOpen to true but the menu in the child directive is not updating?

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


Solution

  • The main issue in your implementation is that you want to use the the $scope to share the value of menuOpen between the parent and child directive, but your parent directive has an isolated scope :

    scope: {
      menuOpen: '@menuOpen'
    }
    

    You need to declare menuOpen in a scope shared by both directives, due to transclusion it has to be the parent scope of the parent directive. So, in the parent directive you should not create a new scope :

    scope: false,
    link: function($scope) {      
      $scope.menuOpen = false;
      $scope.toggleMenu = function() {
        $scope.menuOpen = !$scope.menuOpen;
      };
    }
    

    Then, openMenu is accessible in the child directive. See it in in a fork of your Plunker.