Filip Witkowski
Filip Witkowski

Reputation: 965

Child directive not updated when parent directive property changes

This is follow up to these 2 questions:

  1. Pass argument between parent and child directives
  2. Parent directive controller undefined when passing to child directive

I have this part working; however, when the value for ng-disabled for parent directive changes, the child directive values don't get updated.

Please see thin plunkr example.

HTML:

<div ng-app="myApp">
  <div ng-controller="MyController">
    {{menuStatus}}
    <tmp-menu ng-disabled="menuStatus">
      <tmp-menu-link></tmp-menu-link>
      <tmp-menu-link></tmp-menu-link>
    </tmp-menu>
    <button ng-click="updateStatus()">Update</button>
  </div>
</div>

JavaScript(AngularJS):

angular.module('myApp', [])
.controller('MyDirectiveController', MyDirectiveController)
.controller('MyController', function($scope){
  $scope.menuStatus = false;
  $scope.updateStatus = function(){
    $scope.menuStatus = $scope.menuStatus?false:true;
  }
})
.directive('tmpMenu', function() {
  return {
    restrict: 'AE',
    replace:true,
    transclude:true,
    scope:{
      disabled: '=?ngDisabled'
    },
    controller: 'MyDirectiveController',
    template: '<div>myDirective Disabled: {{ disabled }}<ng-transclude></ng-transclude></div>',
    link: function(scope, element, attrs) {


    }
  };
})
.directive('tmpMenuLink', function() {
  return {
    restrict: 'AE',
    replace:true,
    transclude:true,
    scope:{
    },
    require:'^^tmpMenu',
    template: '<div>childDirective disabled: {{ disabled }}</div>',
    link: function(scope, element, attrs, MyDirectiveCtrl) {
      console.log(MyDirectiveCtrl);

      scope.disabled = MyDirectiveCtrl.isDisabled();

    }
  };
})

function MyDirectiveController($scope) {
  this.isDisabled = function() {
    return $scope.disabled;
  };
}

How can I detect change in parent directive and pass it to child directive without adding angular watcher.

Upvotes: 0

Views: 1578

Answers (1)

Karim
Karim

Reputation: 8632

Solution 1

i've set up a working plnkr here: https://plnkr.co/edit/fsxMJPAc05imhBqefaRk?p=preview

the reason of this behaviour is that tmpMenuLink kept a copy of the value returned from MyDirectiveCtrl.isDisabled(). no watcher is set up , so the only way to resolve this is to manually watch for any changes and then update the field.

scope.$watch(function(){
  return MyDirectiveCtrl.isDisabled();
}, function(){
   scope.disabled = MyDirectiveCtrl.isDisabled();
})

Solution 2

An alternative without watchers is to pass the reference of an object instead of a primitive type, something like:

$scope.menuStatus = {status: false};

new plnkr here: https://plnkr.co/edit/RGEK6TUuE7gkPDS6ygZe?p=preview

Upvotes: 1

Related Questions