angular / angular.js

AngularJS - HTML enhanced for web apps!
https://angularjs.org
MIT License
58.85k stars 27.52k forks source link

How to get required controller? #10998

Closed piernik closed 9 years ago

piernik commented 9 years ago

Here is sample from my directive with my problem

return {
    restrict: "E",
    require: "^directive1",
    controller: 'myCtrl',
    controllerAs: "vm",
    bindToController: true,
    link: function (scope, element, attrs, directive1Ctrl) {

    }
};

function myCtrl() {
    //how to get to required (directive1Ctrl) controller ??
}

How to get required directive1Ctrl in myCtrl??

ericmdantas commented 9 years ago

Have you tried:

angular
.module('youAppName')
.controller('myCtrl', function()
{
    // controller stuff goes here
})
matsko commented 9 years ago

No he means that how can he gain access to the parent controller within his own controller.

One way I know how to do this is to use an injected $element, but I can't say for sure if this way is considered a best practice since you're using an element within a controller.

.controller('myCtrl', ['$element', function($element) {
   var parentCtrl = $element.parent().controller('diective1');
}])
gkalpak commented 9 years ago

Another workaeound would be using the link function (and if necessay pass the parent controller to the element's controller). But it would indeed be nice to have the required controllers as injectables in the element's controller.

dorellang commented 9 years ago

+1 to gkalpak It's kind of weird that you can access parent controllers by the link function, but not by the controller itself. The later seems to suit better the component oriented approach that Angular is embracing in the latest versions.

piernik commented 9 years ago

I think that injecting required controller is essential to fullfill new style of not using $scope in controller in favour of this

piernik commented 9 years ago

@matsko - Your solution works great!

Narretz commented 9 years ago

There's an issue with some discussion about this, let's move it here: https://github.com/angular/angular.js/issues/5893

One good point that is raised that injecting controllers into controllers might create circular dependencies.