Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular reusable functions

Tags:

angularjs

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?

like image 618
supermasher Avatar asked Jul 21 '26 07:07

supermasher


1 Answers

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.
        };
    };
});
like image 193
Umur Kontacı Avatar answered Jul 25 '26 13:07

Umur Kontacı



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!