Reputation: 3
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)
Upvotes: 0
Views: 48
Reputation: 68635
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;
})
};
]})
Upvotes: 1
Reputation: 15104
Angular don't inject dependencies in the link function, you have to take it in the function declaration of the directive itself :
angular.directive('myDirective', function(myService) {
return {
// ...
link: function(...) {
myService.addFavorite(objectId, currentUser);
}
}
});
Upvotes: 0