Issue
Can I, from a directive or component, require a controller that is not from another directive or component?
Here is what I have tried:
Attempt 1
Throws Injector Error.
angular.module('test', [])
.controller('mainController', function(){
this.someData = [{
someKey : Math.random()*10
}];
this.someFunction = function(data){
this.someData.push(data);
}
})
.component('master', {
require:{
main:'mainController'
},
controller:function(){
this.$onInit = function(){
console.log(this);
}
}
});
Attempt 2
Creates a new copy of the controller – not what I need.
angular.module('test', [])
.controller('mainController', function(){
this.someData = [{
someKey : Math.random()*10
}];
this.someFunction = function(data){
this.someData.push(data);
}
})
.component('master', {
controller:function($controller){
this.$onInit = function(){
this.main = $controller('mainController');
console.log(this);
}
}
});
To see what I mean in the second example, please see This Plunkr.
I doubt there is a way, but if I'm honest I've never fully looked into how angular does what it does. Odds are you have to create a new component/directive and you can just include its controller from there, but I was hopeful!
Solution
ng-controller is a directive. So regarding the abilities, the nearest controller can be required with
require: '^ngController'
It is not necessarily main controller, just some controller.
And regarding 'best practices', it can't, this smells bad. The code above needs no main controller at all. If there should be some global someData
and someFunction
- make them a service (or two). It can be injected to any component controller then, disregarding their places in DOM hierarchy.
Answered By - Estus Flask
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.