passing value from parent directive to child directive's template function

2.8k Views Asked by At

I'm trying to access value that is passed from the parent's directive on the child directive's template function.

Please refer to the below plunker.

Plunker Link

CODE:

Parent Directive:

directive('parentDir', function(){
  return {
    controller: ['$scope',function($scope){
      $scope.myVal = 'HELLO';
    }],
    templateUrl: 'parentDir.html'
  }
})

Child Directive:

directive('childDir', function(){
  return {
    template: function(element,attrs){
      alert(attrs.val);
    }
  }
})

parentDir.html:

<div>
  <child-dir val="{{myVal}}"></child-dir>
</div>
1

There are 1 best solutions below

2
Chantal On

You can add the val attribute to the directive like this:

.directive('childDir', function(){
  return {
    restrict: 'E',
    scope : {
      val : '='
    },
    link : function(scope, element, attrs) {
      return alert(scope.val);
    }
  }
})

Here is a working plunkr