What is the best way to invoke a Service from a Directive in AngularJS?

Every time a user clicks, a directive is triggered to change the icon for adding to their 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 would like to make a service call from this directive when the click event occurs, similar to how it is done from a controller. Here is an example of the service I want to invoke

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

Answer №1

One important thing to note is that Angular does not automatically inject a service into the link function. You will need to manually inject your service into the directive and then use it just like you would in a controller.

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

   // Here is where you can utilize PlaceService 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;

       })

     };
 ]})

Answer №2

When working with Angular, it's important to remember that dependencies are not injected directly into the link function. Instead, they need to be included in the function declaration of the directive itself:

angular.directive('myDirective', function(myService) {
    return {
        // ...
        link: function(...) {
            myService.updateData(dataId, newData);
        }
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create an input field with a dynamic and exclusive identifier using the DataTables plugin

I am having trouble creating unique IDs for each input field based on the number of rows Here is the code snippet: $(document).ready(function() { var oTable = $('#jsontable').dataTable(); //Initialize the datatable $.ajax({ url ...

Removing other objects with Mongoose after an update

I'm facing an issue with my update query in mongoose. I can't figure out why other objects are getting deleted when I only intend to update one specific object. The code is functioning correctly in terms of updating, but it's causing all the ...

Creating personalized functions in Object.prototype using TypeScript

My current situation involves the following code snippet: Object.prototype.custom = function() { return this } Everything runs smoothly in JavaScript, however when I transfer it to TypeScript, an error surfaces: Property 'custom' does not ex ...

What is Angular's approach to handling a dynamic and unprocessed JSON object?

When a JSON file is placed under assets, accessing it using something like http://localhost:4200/myapp.com/assets/hello.json will fetch the JSON file directly without any graphical user interface. This indicates that Angular must be able to return a raw JS ...

React - Updating the Color of a Specific Div within a Map Component

Currently, I am delving into React and Material UI and facing an issue with changing the background color of a clicked div. As it stands, all the divs are being affected when one is clicked. My goal is to have the background color transition from white to ...

Rails 5 not allow user submission of bootstrap modal form

I am facing an issue with a form inside a modal in my Rails application. When I click on the submit button, nothing happens. How can I use Ajax to submit the modal form and save its content on another page? <button type="button" class="btn btn-primary ...

The image fails to load when attempting to retrieve it from a local JSON file

I successfully managed to fetch data dynamically from a local JSON file created in RN. However, when I tried to add images for each profile to be displayed along with the dynamic profile info, the app encountered an error stating that "The component cannot ...

Obtaining a data point by referencing a key within a json collection

I am working on an AngularJS function that includes a JSON array like this: $scope.userDetails = [{ name: 'Anil Singh', age: 30 }, { name: 'Reena Singh', age: 25 }]; My goal is to extract all the values of the age key. Here is the co ...

Solving the issue of overflowing in the animation on scroll library

I've recently started using a fantastic library called animation on scroll (aos) for my web development projects. This library offers stunning and visually appealing animations. However, I encountered an issue where it causes overflow problems in my H ...

Warning in Google Script editor

Currently, I am working on creating some quick scripts to manipulate spreadsheets in my Google Drive. However, I am cautious about the script unintentionally running and making changes to data before I am ready or executing multiple times after completing ...

Having trouble accessing the data I'm setting in a separate component using the Context API

Currently working on my own project and I've encountered a problem while using the Context API. It's my first time using it. The issue I'm facing is that I can't seem to console.log the data I'm setting. I'm trying to create ...

accurate JSONP reply

Currently, I am experimenting with JSONP locally to receive a correct response and pass it into my callback function jsonp_callback. I am referencing code from: How do I set up JSONP? header('content-type: application/json; charset=utf-8'); $dat ...

What is the best way to transfer a JavaScript object to a VueJS component?

Even though it may seem like a basic question, I'm having trouble figuring out how to accomplish this in VueJS Here's the code I have in HTML: <script> var config = {'cols':4,'color':'red'} </script> ...

Converting HTML content into a single string simplifies data manipulation and extraction

exampleHTML=" This is sample HTML code that needs to be converted into a string using JavaScript

" I am looking to transform it into a single string format like str="This is sample HTML code, that needs to be converted into a string, usin ...

If I am already in the child router and attempt to refresh the browser, I will not be able to load

This is a custom router configuration for student enrollment. var studentEnroll = { name: 'student-enrollment', label: "Enroll Student", url: '^/home/students/enroll', par ...

Having trouble uploading a file to Laravel using the jQuery .post method?

Here is a snippet of my HTML code: <input type="file" class="form-control" name="file-name" id="file-id"> This is the JavaScript function that is meant to send the file to an API: var file = $('input#file-id').val(); $.post('my/url/ ...

Difficulty in toggling on and off several form elements with JavaScript

Trying to control multiple form elements on an HTML page with JavaScript has presented a challenge for me. In my form, each row contains a checkbox that should enable/disable the elements on that row. The issue I'm facing is that only the first two f ...

Sort by label using the pipe operator in RxJS with Angular

I have a situation where I am using an observable in my HTML code with the async pipe. I want to sort the observable by the 'label' property, but I'm not sure how to correctly implement this sorting logic within the pipe. The labels can be e ...

What could be the reason for the Azure server sending a Bad Request response?

My NodeJS application is currently hosted on Azure server and all APIs are functioning correctly, providing the expected responses. The issue arises when trying to run a GET API like the following: https://demoapp.azurewebsites.net/mymenu?userId=piyush.d ...

Is there a quicker method than using document.getElementById('element-id').innerHTML to retrieve content?

Currently, I am developing a user-friendly step-by-step wizard for my website to gather information about custom orders. Utilizing JavaScript, I have been tasked with updating the content of each "page" using the document.getElementById('element-id&ap ...