I have a simple code:
define(['app'], function(app)
{
app.factory('factoryProvider', function(){
return {
name: 'my Name'
}
});
app.directive('myDiv',['factoryProvider', function(factoryProvider) {
return {
restrict: 'E',
replace: true,
templateUrl: 'link/to/template.html',
controller: function($scope) {
},
link: function(scope, routeParams, location) {
console.log(factoryProvider.name);
}
};
}])
});
I want to be able to access myFactory
within the link
function, but I can't! I also tried link: function(scope, routeParams, location, factoryProvider)
and that also didn't work. Why?
Link: The link function deals with linking scope to the DOM. Using Code for Compile. While defining a custom directive we have the option to define a link against which either we can define a function or we have the option to assign an object which will have pre & post function.
You can do injection on Directives, and it looks just like it does everywhere else.
Answer: D is the correct answer. The "Application Module" can be injected as a dependency in AngularJS.
It should already be available inside the link function
app.factory('factoryProvider', function(){
return {
name: 'my Name'
}
});
app.directive('myDiv',['factoryProvider', function(factoryProvider) {
return {
restrict: 'E',
replace: true,
template: '<p>{{name}}</p>',
controller: function($scope) {
},
link: function(scope) {
scope.name=factoryProvider.name;
}
};
}]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With