Reputation: 9752
{
controller: 'myController',
templateUrl: '/templates/my-template.html',
restrict: "E",
};
Is there any way that I can add an object in the injector so that it's available inside myController? I know angular bootstrap does this with it's "resolve" attribute, when it news up a controller, so I would like to know if there's a way to do this here. And yes, I realize I can make this object available to the controller by setting it on the scope property, but I would like to know if I can do this through the injector rather than scope.
Upvotes: 0
Views: 40
Reputation: 49590
There is a way to manually create a controller and supply dependencies with $controller
, however in case of passing the object from the link
function to the controller
in the directive (as seems to be in your case) there is an easier way and one does not need to pollute the scope to achieve that.
All that is needed is to obtain the reference to the already instantiated controller. This is simply done with require
of own controller:
.directive("foo", function(){
return {
require: "foo",
controller: function($scope){
//...
},
link: function(scope, element, attrs, fooCtrl){
fooCtrl.someObj = {a: "aaa"};
}
}
});
Unlike the "resolved" value, this object is not available when the controller function runs. This is rarely needed though. If you need, however, to perform some initialization only when the object is available, then you can always expose a this.init = function(){...}
function on the controller, and invoke it as needed.
Upvotes: 1
Reputation: 19193
You can create a service and inject it in your controller. Let's say the service is called "myObject"
, you can then define your controller as:
controller: function($scope, myObj) {
// myObj is accessible in the controller
}
Upvotes: 0