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

Issue with Node.js xml2js module: Sitemap attributes are not being recognized during creation

Currently, my project involves utilizing node.js and xml2js to generate an XML sitemap.xml. Everything seems to be in order, but when I try to define attributes like: '$': { 'xmlns': 'http://www.sitemaps.org/schemas/sitemap/0 ...

Having trouble setting the image source in HTML with Node.js

I am a beginner with nodeJS and I am having trouble setting the src attribute of an img tag in my client side html. My node server is running on port 3000 and everything works fine when I visit http://localhost:3000. Here is the code from my server.js fil ...

Invoking vscode Extension to retrieve data from webview

One task I'm currently working on involves returning a list from the extension to be displayed in the input box of my webview page. The idea is for a JavaScript event within the webview to trigger the extension, receive the list object, and then rend ...

Component experiencing issues with service or @Input functionality

I have been struggling with importing a service inside a component and encountering an issue where the Input from the service does not render anything in the template. Let's take a look at my entity: export interface PageState { step: string; } e ...

Add a click event listener to the body element using a button click, without causing it to trigger

What is the current situation: A button is clicked by the user The menu opens (list items display = block) The function to close the menu is connected to the <body> The function to close the menu is immediately triggered, causing the menu to close ...

Adding to object properties in Typescript

My goal is to dynamically generate an object: newData = { column1: "", column2: "", column3: "", ... columnN: "" } The column names are derived from another array of objects called tableColumns, which acts as a global variable: table ...

JSP form continues to submit despite JavaScript validation returning false

On my JSP page, I have a form named "deleteCont" and a JavaScript function called "validateDelete". When the user clicks the "Delete contact" button, the "validateDelete" function is triggered successfully, showing an alert message. Unfortunately, even whe ...

Fluctuating and locked header problem occurring in material table (using react window + react window infinite loader)

After implementing an Infinite scrolling table using react-window and material UI, I have encountered some issues that need to be addressed: The header does not stick to the top despite having the appropriate styles applied (stickyHeader prop). The header ...

Efficiently managing AJAX requests in PHP

One aspect of my work involves a substantial amount of UI coding that requires sending AJAX requests to the backend PHP. I've been managing this by using: if(isset($_REQUEST["UniquePostName"])){ /* Do Something*/ } if(isset($_REQUEST["AnotherUniqueP ...

Getting the parameter route value from Laravel and passing it to Ajax

Need help with returning the parameter of a Laravel route to an AJAX response. Here is the relevant code: public function getPermissions(Request $request) { //$v = request()->route()->parameters('profile'); $v = request()-& ...

Problem with image title in jQuery mobile

My code seems to be having an issue where the title does not display completely when hovering over it. For example, if the title is set as "The Value", only "The" is shown and not "The Value". Can anyone help me identify the mistake? Thank you in advance ...

A guide on personalizing HTML for Django forms

I have implemented an HTML template on my website and need to capture information for my Django backend. Specifically, I am trying to extract the email address from this section of code: <input type="text" placeholder="Email" value="" style="height: 30 ...

Unable to generate two tables

I have a dynamic table creation issue. The tables are meant to be created based on the user's input for the "super" value. For example, if the user inputs "2" for super, then it should create 2 tables. However, this is not happening as expected becaus ...

Is Jquery not tallying up the numbers accurately?

Looking to secure a ticket with a complimentary offer? Here are the guidelines: A single individual can purchase 1 or more tickets, but the maximum is 4 An offer of at least 1 euro can be made for tickets, with no upper limit. For instance, if 4 tickets ...

Kendo UI Scheduler: The system encountered an overflow while converting to a date and time format

Working on a project using .NET MVC and the Kendo UI Scheduler, an open-source tool. The goal is to save, read, update, and delete events from the scheduler into the database using JavaScript. Encountering some challenges in the process - when attempting ...

Clustering in an environment requires merging and minifying granules

While Granule is effective for minifying and merging CSS/JS files on a local environment, it presents challenges in clustered environments. The issue arises when each node of the cluster computes its own file during runtime, causing discrepancies when a us ...

Accessing form data within Mongoose schema hooks via JavaScript

I have a form where I've split the content into two separate MongoDB schemas. I want to access variables that are within node.js/express.js directly in mongoose schema hooks, whether through pre or post hooks of the schema. Here are my files: expres ...

Efficiently managing classes with css modules and extractCSS in Nuxt 2

When using Nuxt 2 with CSS modules, I encountered an issue where multiple components resulted in multiple CSS files having the same class. Hello.vue <template> <div :class="$style.title">Hello, World</div> <div :class=&q ...

Removing a value from an array contained within an object

I have a scenario in my task management application where I want to remove completed tasks from the MongoDB database when a logged-in user marks them as done. Below is the snippet of code for my Schema. const user = new mongoose.Schema({ username : Str ...

JQuery is unable to validate a form that is being loaded from an external HTML file

I'm encountering an issue where my form imported into a separate HTML file is not validating using JQuery's $(form).validate() plugin. After following the guidance provided in this question, I successfully managed to get the form working. Howeve ...