ThinkBonobo
ThinkBonobo

Reputation: 16525

Inject factory into directive's link function defined OUTSIDE of the directive's scope

I saw the following question (among other similar questions) and it solves the problem of trying to inject a factory into a directive's link function: Injecting service to Directive

The solutions I've seen keep the link function within the scope of the directive:

angular.module('myapp')
    .directive('myDir', function(myService){
        return {
            restrict: 'E',
            scope: {
                frame: '='
            },
            link: function postLinkFn(scope, elem, attr) {
                myService.doSomething();
            }
        };
    });

However, I want to be able to separate the postLinkFn outside of the .directive scope for organization, just like I can do with controllers.

Is it possible to separate this function while also injecting a service into it?

Upvotes: 4

Views: 1876

Answers (2)

Estus Flask
Estus Flask

Reputation: 222795

.directive('myDir', function(myService){
    var deps = { myService: myService };

    return {
        ...
        // myService is available as this.myService inside postLinkFn
        link: angular.bind(deps, postLinkFn)
    };
});

link function doesn't make use of dependency injection and doesn't have lexical this, binding injected dependencies to this is a reasonable move.

Upvotes: 5

Sachin Siwach
Sachin Siwach

Reputation: 90

Sure you can put your code in a factory and then refer it globally across the app.

angular.module('myapp').factory('myfactory', myService, function(){
return{
var myfac;
my fac = function (myService){
  var myItem = myService.doSomething;
  return myItem;
};

};
}).
.directive('myDir', function(myService){
    return {
        restrict: 'E',
        scope: {
            frame: '='
        },
        link: myfactory.myItem;
    };
});'

Just a little care you need to take is binding your factory with an angular promise $q if your service deals with asynchronous calls.

Upvotes: 1

Related Questions