Jason
Jason

Reputation: 129

How can I access the function in child directive which passed from parent directive but defined in controller?

I have a parent directive and a child direcive, all in a controller, view is here:

<body ng-app="myApp">
  <section ng-controller="TestController">
     <section parent-directive parentFn="callback">
       <child-directive>
         <button ng-click="save()">save</button>
       </child-directive>
     </section>
  </section>
</body>

I want to access the callback function which defined in TestController but passed into the parentDirective and then passed into the childDirective.

my js code:

var myModule = angular.module('myApp', []);
myModule.controller('TestController', function($scope) {

  $scope.callback = function(){
    console.log('callback invoked');
  };
});


myModule.directive('parentDirective',function(){
    return {
    restrict: 'EA',
    scope: {
        parentFn: '&'
    },
    controller: function($scope){
        this.parentFn = $scope.parentFn;
    }
  }
});

myModule.directive('childDirective',function(){
    return {
    restrict: 'EA',
    require: '?^parentDirective',
    transclude: true,
    template: '<div ng-transclude></div>',
    link: function(scope, element, attrs, controller){
        console.log("child:c:%o",controller);
        scope.save = function(){
        console.log('save fn invoked');
        console.log('is parentFn type:%o',typeof controller.parentFn);
        controller.parentFn();
      }
    }
  }
});

here is a jsfiddle: https://jsfiddle.net/savokiss/j6gp720c/

And when I click the button the callback invoked does not appear in my console.

Why?

Upvotes: 2

Views: 122

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136134

You are not passing the function in directive element correctly, Directive attribute name should be in small case and then Uppercase should be converted with small case with prefixed hyphen. like here parentFn should be parent-fn and then its value should have the method call.

 <section parent-directive parent-fn="callback()">
   <child-directive>
     <button ng-click="save()">save</button>
   </child-directive>
 </section>

Fiddle

Upvotes: 4

Related Questions