Jakub Kolčář Jakub Kolčář - 4 months ago 14
Javascript Question

Using service inside directive?

I am learning creating custom directives.

I have service like that:

myApp.service('myService',function(){
this.myFunction=function(myParam){
// do something
}
});


I have a directive like that:

myApp.directive('myDirective',function(myService){
return {
restrict: 'E',
scope: {
param: '=myParam',
},
template: '<button ng-click="myService.myFunction(param)">Do action</button>',
}
});


When in HTML I use
<my-directive my-param="something"></my-directive>


it properly renders as a button. However when I click it, myService.myFunction, doesn't get executed.

I suppose I am doing something wrong. Can someone give me a direction?
I guess this has something to do with the directive's scope.

Answer

The service wont be available directly inside the template. You'll have to use a function attached to the directive's scope and call the service function from within this function.

myApp.directive('myDirective',function(myService){
    return {
        restrict: 'E',
        scope: {
          param: '=myParam',
        },
        template: '<button ng-click="callService(param)">Do action</button>',
        link: function(scope, element, attrs) {
            scope.callService = function() {
                myService.myFunction();
            }
        }
    }
});
Comments