Inject factory to the directory link function defined by OUTSIDE for the scope of the directive

I saw the following question (among other similar questions) and solves the problem of trying to insert a factory into a directory link function: Engineering into the Directive

The solutions I saw support the link function as part 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 share postLinkFn outside of the .directive scope for the organization, just as I can do with controllers.

Is it possible to separate this function, as well as introduce a service into it?

+4
source share
2 answers
.directive('myDir', function(myService){
    var deps = { myService: myService };

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

link this, this .

+5

, factory, .

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;
    };
});'

, factory angular $q, .

+1

Source: https://habr.com/ru/post/1615058/


All Articles