Snave337 Snave337 - 1 month ago 5
Javascript Question

How can I call a Service from a Directive in AngularJS

I currently have a directive that is called whenever a click event happens. This helps me change the icon for adding to user's favorite list.

View:

<div class="col col-33">
<i class="icon ion-ios-heart-outline" favorite="place[0].objectId" on-icon="ion-ios-heart-outline" off-icon="ion-ios-heart" icon-switcher /></i>{{place[0].likes}}
</div>


Directive:

.directive('iconSwitcher', function() {

return {
restrict : 'A',
scope: {
favorite: '='
},
link : function(scope, elem, attrs, PlaceService, ) {

var currentState = true;

elem.on('click', function() {
console.log('objectId',scope.favorite);
if(currentState === true) {
angular.element(elem).removeClass(attrs.onIcon);
angular.element(elem).addClass(attrs.offIcon);
} else {
angular.element(elem).removeClass(attrs.offIcon);
angular.element(elem).addClass(attrs.onIcon);
}

currentState = !currentState

});


}
};});


I will like to call a service from this directive when the click event happens like i do from a controller. Here is a sample of the service i want to call

$scope.addFavorite = function(objectId){
PlaceService.addFavorite(objectId,currentUser)

Answer

Angular will not inject the service into the link function.Inject your service in the directive and use like in the controller.

.directive('iconSwitcher', ['PlaceService', function(PlaceService) {

   // Use PlaceService here as a simple service

   return {
      restrict : 'A',
      scope: {
        favorite: '='
      },
      link : function(scope, elem, attrs) {

         var currentState = true;

         elem.on('click', function() {
             console.log('objectId',scope.favorite);
             if(currentState === true) {
                angular.element(elem).removeClass(attrs.onIcon);
                angular.element(elem).addClass(attrs.offIcon);
             } else {
               angular.element(elem).removeClass(attrs.offIcon);
               angular.element(elem).addClass(attrs.onIcon);
             }

         currentState = !currentState;

       })


     };
 ]})
Comments