What is the process for invoking a function using a directive's service in Angular?

manager

angular.module('myApp')
  .controller('myCtrl', [  '$mdDialog', '$mdMedia', 'viewDialog', myCtrl]);
..

function myCtrl(  $mdDialog, $mdMedia, viewDialog) {   
    $scope.openView = function(ev,id) {
        viewDialog.showItemModal(ev,id)
    };
}

template

<div ng-controller="myCtrl">
  <md-list-item ng-repeat="item in itemsList">
     <a  open-view-dialog">
       <h4> {{item.id}} </h4>
     </a>
  </md-list-item>
</div>

When I trigger the function directly from controller, the modal window opens correctly on click

using a custom directive

The provided directive

angular.module('myApp')
    .directive('openViewDialog', function ($parse) {
        return {
            compile: function(tElm,tAttrs){
              var exp = $parse('openView($event,item.id)')
              return function (scope,elm){
                elm.bind('click',function(){
                  exp(scope);
                });
              };
            }
        };;
    });

Now I aim to eliminate the controller dependency and call the viewDialog service directly from the directive, but it is not functioning.

Below is the modified code for service injection

angular.module('myApp')
    .directive('openViewDialog', function ($parse, viewDialog) {
        return {
            compile: function(tElm,tAttrs){
              var exp = $parse('viewDialog.showItemModal($event,item.id)') 
          return function (scope,elm){
                elm.bind('click',function(){
                  exp(scope);
                });
              };
            }
          };;
    });

Answer №1

Why not give this a shot?

.directive('myViewDialog', function ($parse, viewDialog)

Or maybe try this:

.directive('myViewDialog', [ '$parse', 'viewDialog', function ($parse, viewDialog)

Answer №2

const myModule = angular.module('myApp')
    .directive('myDialogView',['dialogView','$parse', function (dialogView,$parse) {
    return {
        compile: function(element,attrs){
          var expression = $parse('dialogView.ITEM($event,item.id)') 
      return function (scope,element,attributes,controller){
            element.bind('click',function(){
              expression(scope);
            });
          };
        }
      };;
}]);

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

organize and identify a JSON data using sorting and matching techniques

Having a JSON structure as shown below: [ { "id": "1", "freq": "1", "value": "Tiruchengode", "label": "Tiruchengode" }, { "id": "2", "freq": "1", "value": "Coimbatore", "label": " ...

Module lazily loaded fails to load in Internet Explorer 11

Encountering an issue in my Angular 7 application where two modules, txxxxx module and configuration module, are lazy loaded from the App Routing Module. The problem arises when attempting to navigate to the configuration module, as it throws an error stat ...

Converting text files into JSON format

I am working with a text file that has a specific structure. Title: Tombstone Release Year: 1993 Format: Blu-ray Stars: Kurt Russell, Val Kilmer, Sam Elliott, Bill Paxton Title: The Shawshank Redemption Release Year: 1994 Format: DVD Stars: Tim Robbins, M ...

What is the method for identifying which input field the user has chosen on a web page retrieved from a server?

I attempted the code below without achieving the desired outcome. Any assistance would be greatly appreciated. UIPasteboard *pb = [UIPasteboard generalPasteboard]; [pb setString:passwordName]; NSString *jScriptString; jScriptString = [NSString string ...

Utilize jQuery to animate a div while dynamically altering its width

I've been working on sliding in a div onto the page once it's fully loaded. I initially tried using CSS for this, but the transitions were not as smooth as I wanted them to be. That's when I decided to switch to jQuery. The transition is mu ...

Function activation in Element requires a double click to initiate

I've encountered an issue with a web element I'm working on where the click function only triggers after the first click, rendering the initial click ineffective. Here's the code snippet in question: HTML: <div> <a href="#0" cla ...

Building an array from scratch in Angular

Below is the URL to access the code: https://stackblitz.com/edit/ng-zorro-antd-start-xz4c93 Inquiring about creating a new array. For example, upon clicking the submit button, the desired output should resemble the following structure: "tasks": [ { ...

jQuery class toggle malfunction

I have a series of list items with specific behavior when clicked: Clicking a list item will select it and add the class .selected If another list item is clicked, the previously selected item becomes unselected while the new one becomes selected If a se ...

React components multiplying with every click, tripling or even quadrupling in number

My app enables users to create channels/chatrooms for communication. I have implemented a feature where pressing a button triggers the creation of a channel, using the function: onCreateChannel. Upon calling this function, the state of createChannel chan ...

Iterate through the array in order to showcase or output it in PHP syntax sourced from an API

[0] => Array ( [id] => 6 [name] => Digitally Imported Psy Goatrance [country] => GB [image] => Array ( [url] => https://img.dirble.com/station/6/original.png ...

What is the process for retrieving the data from the POST request body on the client side?

Greetings to all, I am a student who is still in the process of learning and have a question about passing data from server to client. Currently, I have an Arduino sensor that sends POST requests containing sensor data to an express server. The server suc ...

The functionality of tinymce setContent can only be activated by directly clicking on it

Everything is running smoothly with the code below: $('.atitle').on('click', function(){ console.log('323'); tinymce.get("ed").setContent("<p>lorem ipsum</p>"); // it's working ...

Preventing Event Loop Blocking in Node.js: The Key to Streamlining Performance

I am currently working on developing two APIs using Express.js. The tasks for both APIs are quite straightforward. The first API involves running a for loop from 1 to 3,000,000, while the second API simply prints a string in the console. All the necessary ...

What is the best way to show notifications in a component using react-alert?

Currently working with reactjs and looking to display alerts within a component using the react-alert module. Find more information about react-alert here. I have followed the provided instructions to wrap the index.js file. However, when attempting to ut ...

Convert a JSON array into a JavaScript array?

Similar Question: How can I extract property values from a JavaScript object into an array? I am receiving a JSON array from a basic server and need to parse it into JavaScript for use in my web application. What is the best way to convert a JSONP ar ...

After a short delay, make sure to open a new tab when clicking to bypass any popup blockers without relying on Ajax technology

Before you downvote, please consider my rationale. I am in the process of developing a web-based educational project that includes an art section. When a user clicks on a button, an element containing a picture of an art piece appears. I then want to open ...

There was an issue retrieving the user with a particular email and status in mongodb

I am trying to retrieve a user order with a specific email and status that is not equal to "Order Completed". However, I am encountering an error stating "Expression $ne takes exactly 2 arguments. 1 were passed in." It would be greatly appreciated if someo ...

Unable to align span vertically using font-style "Luckiest Guy" in CSS

I have encountered an issue with vertically centering a span using the font-style "Luckiest Guy". https://i.sstatic.net/Lz8o3.png I attempted to use display: flex;align-items: center; on the span, but it did not work. App.vue <template> <div ...

Exploring cookie management in AngularJS using the $http service

Currently, I am facing a challenge in implementing authentication using ExpressJS' cookie sessions and AngularJS. The issue I am encountering is that even though I have managed to get ExpressJS to send session cookies, Angular does not send them with ...

Uncovering data from a dynamic website through the combination of Selenium and PhantomJS

I am attempting to obtain the timer value from this website http://prntscr.com/kcbwd8 located at , and ideally save it in a variable. import urllib from bs4 import BeautifulSoup as bs import time import requests from selenium import webdriver from urllib. ...