javascript - Pass parent directive's controller to a directive controller (like it is done in the "link" function) -


i have several hierarchical directives , in one, need have functions in controller, child elements can interact it. 1 directive needs reference parent directive's controller, don't know how in controller (i know how in "link()" time need controller child interaction). should possible scope:

controller: function($scope){}, link: function (scope, ..., parentctrl){     scope.parentctrl = parentctrl; } 

but seems weird, because link function executed after controller is, or it ok? i'm confused , think might bad design?

diagram:

parentparentdirective     controller: function(service){         this.service = service;     }  parentdirective     controller: function(){         this.callonservice = function(id){             ???parentparentdirective???.service.callsth(id);         }     }  childdirective     link(scope, ...,parentdirectivectrl){         scope.makechanges = parentdirectivectrl.callonservice;     } 

you can use $element.controller method that, in example below.

angular.module('app', []);    angular.module('app').directive('grandparent', function () {    return {      restrict: 'e',      controller: function () {        this.go = function () {          console.log('grandparent directive');        };      }    };  });      angular.module('app').directive('parent', function () {    return {      restrict: 'e',      controller: function () {        this.go = function () {          console.log('parent directive');        };      }    };  });    angular.module('app').directive('child', function () {    return {      restrict: 'e',      require: ['^parent', '^grandparent'],      controller: function ($element) {        var parentctrl = $element.controller('parent');        var grandparentctrl = $element.controller('grandparent');                parentctrl.go();        grandparentctrl.go();      }    };  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>  <div ng-app="app">    <grandparent>      <parent>        <child></child>      </parent>    </grandparent>  </div>


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -