Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a require'd controller from another controller?

I have an Angular 1.3 module that looks something like this (directive that requires the presence of a 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 into $scope here
    link: function link(scope, element, attrs, parentDirectiveCtrl) {
      scope.parentDirectiveCtrl = parentDirectiveCtrl;
    },
    controller: 'FooController',
    controllerAs: 'controller',
    bindToController: true,
    require: '^parentDirective'
  };
});

Here I'm just using $scope to pass through parentDirectiveCtrl, which seems a little clunky.

Is there another way to access the require-ed controller from the directive's controller without the linking function?

like image 339
thatmarvin Avatar asked Apr 28 '26 21:04

thatmarvin


1 Answers

You must use the link function to acquire the require-ed controllers, but you don't need to use the scope to pass the reference of the controller to your own. Instead, pass it directly to your 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 the controller runs prior to link, so within the controller this.parent is undefined, until after the link function runs. If you need to know exactly when that happens, you can always use a controller function to pass the parentDirective controller to:

link: function link(scope, element, attrs, ctrls) {
  //...

  me.registerParent(parent);
},
controller: function(){
  this.registerParent = function(parent){
    //...
  }
}
like image 108
New Dev Avatar answered Apr 30 '26 10:04

New Dev