Saeed Habibi
Saeed Habibi

Reputation: 348

AngularJS directive, Call service by directive attribute

I'm trying to create an angular directive for calling service method to check changing database.

Here is my HTML:

<div my-directive="Panel.check"></div>

What I'm want:

Call "check" method of "Panel" service. Directive don't know anything about services and its method. It just parses attributes and binds them, Or if must be injected show me the solution.

What I have:

appDirectives.directive('myDirective', function($parse) {

var directiveOnObject = {
    restrict: 'A',
    scope: { method:'&myDirective' },
    link: function(scope,element,attrs) {

        var panel = scope.method;

        console.log(panel());
    }
};  

return directiveOnObject;

});

Scope method should get instance of "Panel" and call "check" method of it.

Is there any solution to this? Please explain.

Upvotes: 0

Views: 1415

Answers (2)

Jesus Rodriguez
Jesus Rodriguez

Reputation: 12018

You need to have access to the Panel service in the controller, for example:

angular.module('app').controller('Foo', function($scope, Panel) {
  $scope.Panel = Panel;
});

Now you can use your directive, but you when you pass a function with &, you need to put the parens as well:

<div my-directive="Panel.check()"></div>

Without it, it won't work. The rest of the code remains the same.

Check it here

EDIT: If you just need your directive to use one exact service or one exact method, inject the service into the directive like you did with $parse (which is not needed in any case by the way).

EDIT 2: If the service you want to call accepts parameter, you need to do something like:

<div my-directive="Panel.check(param1, param2)"></div>

Then in the directive, you need to map those parameters to your local objects, so if for example (inside your directive) you have:

link: function(scope, element, attrs) {
  var foo = 1;
  var bar = 2;
}

And you want to pass those variables as parameters.

First, you need to recall how you named those parameters in the html, in concrete they were param1 and param2 so you need to do (inside the link function):

scope.method({param1: foo, param2: bar});

So for param1 we pass foo and for param2 we pass bar.

Upvotes: 2

Cristi Marian
Cristi Marian

Reputation: 453

First of all you will need to inject the service in the directive :

appDirectives.directive('myDirective', ['$parse', 'myService', function($compile, myService){
 // here use 'myservice' to get access to variables and methods of the service
}]);

Upvotes: 0

Related Questions