supermasher
supermasher

Reputation: 732

Angular reusable functions

I have several directives that need to call the same function after doing their thing. This function needs to access the main controller scope, but also modify the DOM. How and where should this function be declared?

Upvotes: 3

Views: 6005

Answers (2)

Umur Kontacı
Umur Kontacı

Reputation: 35478

You should use a service, services has access to $rootScope, although is it better to keep DOM modification at directive level, in certain cases you can go for it.

angular.module("myModule", [])
.factory("MyService", function ($rootScope) {
    return {
        myFunction: function () { // do stuff here }
    }
})
.directive("MyDirective", function (MyService) {
    return {
        link: function (scope, iElement, iAttrs) {
            // try do keep dom modification here, you have access to MyService,
            // let it do the algorithm and try to keep dom modification here.
            // PS: you can also inject $rootScope to directives.
        };
    };
});

Upvotes: 7

ŁukaszBachman
ŁukaszBachman

Reputation: 33735

If this function needs to access Controller's scope, I would use the scope which is accessible in the directive and pass it as param, like so:

var MyDirective = function() {
    var linkFn = function(scope, element, attrs) { 
        callAwesomeFn(scope);
    };

    return {
        link: linkFn
    }
};

Now, where to put it?

  • if this is utility function, I would put in some utilities namespace, like MyFunctions.callAwesomeFn()
  • if this is a component which needs to interact with other objects managed by Angular - use Dependency Injection and inject it into directive

Upvotes: -1

Related Questions