3

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?

2
  • Are all the directives placed under the main controller scope? In other words, are all DOM elements which implement those directives inside the element where the Main controller is defined (i.e. <div ng-controller="MainCtrl"><directive1/><directive2/>...</div>)? Commented Feb 13, 2013 at 15:17
  • @bmleite - yes, they are. Commented Feb 15, 2013 at 15:22

2 Answers 2

7

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.
        };
    };
});
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for the solution and example. It's clear to see how my reusable functions may be declared within a service, which may then be passed to the directives that need to access them. Thanks fastreload!
-1

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

1 Comment

Thanks Lukasz, passing the scope to a utility function is exactly what I've done, although it feels a little bit dirty passing the scope outside of angular to achieve my goal. My reusable function calls two other functions; one that modifies the DOM, and another that calls a controller function. I'm not sure if your second suggestion (DI) is suitable for this purpose?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.