javascript - How to access a require'd controller from another controller? -
i have angular 1.3 module looks (directive requires presence of parent directive, using controlleras
):
angular.module('foomodule', []) .controller('foocontroller', function ($scope) { this.dosomething = function () { // accessing parentdirectivectrl via $scope $scope.parentdirectivectrl(); }; }) .directive('foodirective', function () { return { // passing in parentdirectivectrl $scope here link: function link(scope, element, attrs, parentdirectivectrl) { scope.parentdirectivectrl = parentdirectivectrl; }, controller: 'foocontroller', controlleras: 'controller', bindtocontroller: true, require: '^parentdirective' }; });
here i'm using $scope
pass through parentdirectivectrl
, seems little clunky.
is there way access require
-ed controller directive's controller without linking function?
you must use link
function acquire require
-ed controllers, don't need use scope pass reference of controller own. instead, pass directly own controller:
.directive('foodirective', function () { return { require: ["foodirective", "^parentdirective"], link: function link(scope, element, attrs, ctrls) { var me = ctrls[0], parent = ctrls[1]; me.parent = parent; }, controller: function(){...}, }; });
be careful, though, since controller runs prior link, within controller this.parent
undefined
, until after link function runs. if need know when happens, can use controller function pass parentdirective
controller to:
link: function link(scope, element, attrs, ctrls) { //... me.registerparent(parent); }, controller: function(){ this.registerparent = function(parent){ //... } }
Comments
Post a Comment