Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

How to get required controller? #10998

Closed
piernik opened this issue Feb 6, 2015 · 7 comments
Closed

How to get required controller? #10998

piernik opened this issue Feb 6, 2015 · 7 comments

Comments

@piernik
Copy link

piernik commented Feb 6, 2015

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
Copy link

Have you tried:

angular
.module('youAppName')
.controller('myCtrl', function()
{
    // controller stuff goes here
})

@matsko
Copy link
Contributor

matsko commented Feb 6, 2015

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
Copy link
Member

gkalpak commented Feb 6, 2015

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
Copy link

+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
Copy link
Author

piernik commented Feb 7, 2015

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

@piernik
Copy link
Author

piernik commented Feb 7, 2015

@matsko - Your solution works great!

@Narretz
Copy link
Contributor

Narretz commented Feb 8, 2015

There's an issue with some discussion about this, let's move it here:
#5893

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

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

6 participants