Minas Minas
Minas Minas

Reputation: 91

call a global function in directives in ng

i have a function which i call more than once ( in different directives).

So is there a way to call a function in every directive? One solution would be to make the function as a service. But the service does need a return value, doesn´t it?

 this.changeDesign = function (currentstep) {
             //do something
};

this method I call many times.

Upvotes: 2

Views: 354

Answers (2)

hic1086
hic1086

Reputation: 755

you can do it in a directive that you will delcare on your elements.

    angular.module('myDesignModule', [])
     .directive('myDesignDirective', function() {
          return {
               link: function(scope, element, attrs, ctrl){
               element.addClass("myClass");
            }

     };)

Upvotes: 1

jmenzel
jmenzel

Reputation: 130

You should consider to avoid using global variables or put something on the global scope. Maybe it works now, but if your project gets bigger, you will probably get a lot of problems. More infos for example: https://gist.github.com/hallettj/64478

Here is an example, how you can use a factory, which you can inject into your directives (coding style inspired by John Papa https://github.com/johnpapa/angular-styleguide#factories):

(function () {
"use strict";

angular.module('my-app').provider('MyFactory', MyFactory);

    MyFactory.$inject = [];
    function MyFactory() {

        var service = {
            changeDesign: myChangeDesignImpl
        };

        function myChangeDesignImpl() { }

        this.$get = function() {
            return service ;
        };
}

})();

You can now inject your service into a directive like this:

(function () {
"use strict";

    angular.module('my-app').directive('MyDirective', MyDirective);

    MyDirective.$inject = ["MyFactory"];

    function MyDirective(MyFactory) {
       var directive = {
            restrict: 'E',
            template: "/template.html",
            link: link
        };
        return directive;

        function link(scope, el, attr) {
            MyFactory.changeDesign();
       }
    }
})();

Upvotes: 2

Related Questions