Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Injecting Factory into Directive's link function

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 myFactorywithin the link function, but I can't! I also tried link: function(scope, routeParams, location, factoryProvider) and that also didn't work. Why?

like image 829
Kousha Avatar asked Mar 28 '14 18:03

Kousha


People also ask

What is Link function is used for in AngularJS?

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.

Can we inject service in directive in angular?

You can do injection on Directives, and it looks just like it does everywhere else.

Which of the following components can be injected as a dependency in AngularJS factory service value all of the above?

Answer: D is the correct answer. The "Application Module" can be injected as a dependency in AngularJS.


1 Answers

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;
        }
    };
}]);
like image 110
NicolasMoise Avatar answered Oct 11 '22 19:10

NicolasMoise