Organize all ngDialog instances within a factory and access them through a directive

In order to keep the ngDialogs centralized in one place instead of dispersed, I had the idea of creating a factory named modal.js. This factory would contain a list of all the modals with a switch statement. Here is an example:

.factory('Modal', [function() {
        var modal = {};

        return {
          get: function(option) {
            switch(option) {
              case 'modal1':
                modal = {
                  template: 'modal1.php',
                  controller: 'modalController',
                  resolve: {
                    $dep: function() {
                      return 'dep';
                    },
                    dip: function() {
                      return 'dup'
                    }
                  }
                };
                break;

              case 'modal2':
                modal = {
                  template: 'modal2.php',
                  controller: 'modalController2',
                  resolve: {
                    $dep2: function() {
                      return item.dep2;
                    },
                    dip2: function() {
                      return item.dip2;
                    }
                  }
                };
                break;
            }

            return modal;
          }
        }
      }]);

My plan was to then call this factory through a directive, let's name it open-modal.js.

.directive("openModal", ['ngDialog', 'Modal', function(ngDialog, Modal) {
        return {
          restrict: "A",
          link: function(scope, elem, attrs) {
            return elem.bind('click', function() {
              var modal = Modal.get(attrs.modalName) // Modal.get('modal1');
              ngDialog.open(modal);
            });
          }
        };
      }]);

The issue I'm facing is mainly with modal2. I can't retrieve the item from the resolve because it's not part of the controller. My question is: Is there a workaround to maintain this structure?

Thank you for your assistance!

Answer №1

After much thought, I finally cracked the code. My approach involves using $broadcast to trigger the function within each Controller, allowing the resolve to run smoothly.

.factory('Modal', ['$rootScope', function($rootScope) {
  var modal = {};

  return {
    get : function(option, params) {
      switch(option) {
        case 'modal1':
          $rootScope.$broadcast('modal:controller1:modal1');
          break;
        case 'modal2':
          $rootScope.$broadcast('modal:controller2:modal2');
          break;
      }

      return modal;
    }
  }
}]);

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

Creating connections between variables and elements in nested ngRepeats in Angular

I've been facing a challenge with my app where I need to update the comments section whenever a comment is added, edited, or deleted without having to refresh the page. I am using ngResource to handle queries for both articles and comments (e.g. $scop ...

Tips on transforming JSON output into an array with JavaScript

Looking for a solution to convert a Json response into an array using JavaScript. I currently have the following json response: ["simmakkal madurai","goripalayam madurai"]. I need to transform these results into an array format. Any suggestions on how I ...

does not dynamically update hasAttribute

I am encountering an issue with jQuery Validator on my form. Despite being checked or unchecked, the checked attribute does not change on my validator when I submit the form. Below is the snippet of HTML: <div class="col-sm-10 col-sm-offset-1"> ...

javascript Initiate JSON parsing with preset value

In order to parse JSON into a JavaScript object with data, I am providing a simple example below: var IsTrue = true; var Number = 9; var Object = { a : 1}; var Array = [10,6]; var jStr = '{"ask" : IsTrue, "value" : Number, "obj" : Object, "arr" : Ar ...

executing a controller method in AngularJS

Looking to trigger a controller function from a directive tag. Check out this demo: https://jsfiddle.net/6qqfv61k/ When the 'Export to Excel' button is clicked, I need to call the dataToExport() function from appCtrl since the data is ready for ...

Retrieve ALL information from a third-party API request with a limit of 1000 calls

Challenge: Implementation of a third-party API call using Node.JS. The API link restricts the number of users per call to 1000, with an option to retrieve the next set by passing parameters in the URL (?firstResult=1001&maxResults=1000&orderBy=NAME ...

``Do not forget to close the modal window by clicking outside of it or

I am looking for a way to close the modal window either when a user clicks outside of it or presses the escape key on the keyboard. Despite searching through numerous posts on SO regarding this issue, I have been unable to find a solution that works with ...

Error encountered while attempting to save a Mongoose post on Heroku, although it is successful

My aim is to post to my MongoDB Atlas database using node, express, mongoose, and Heroku. While a Postman POST request with Raw JSON body: { "title": "heroku post", "description": "post me plsssss" } works f ...

Is it possible to create a return type structure in TypeScript that is determined by the function's argument?

I'm currently stuck on developing a function that takes a string as an argument and outputs an object with this string as a key. For example (using pseudo code): test('bar') => {bar: ...} I am facing difficulties in ensuring the correct ...

Issue with AnimeJS Motion Path causing element to deviate from desired SVG path

I'm attempting to use an SVG element and the AnimeJS library to make the orange marker follow the course of this RC car race track. https://i.stack.imgur.com/8FKHC.png Despite my efforts, I am encountering strange and undesirable outcomes. At times ...

Searching in sequelize for a specific date using a clause

Operating System: Linux (Lubuntu) Programming Language: Javascript (Node js) Framework: express js Database: mysql "data" represents a Date field from the "activitat" table Upon running this query using Sequelize.js models.TblActivitat.findAll( ...

Having difficulty requesting an API in Next.js that relies on a backend cookie

1: When a user logs in, I generate a refresh token and create a cookie using 'cookie-parser'. This cookie is then sent to the path '/user/refresh-token' res.cookie('refreshtoken', refreshtoken, { httpOnly: true, ...

What could be causing the Material UI tabs to malfunction when dynamically populating the content using a .map function instead of manually inserting it?

I was able to successfully integrate Material UI's tabs by manually adding content, but when I attempted to use a .map function to populate the content from a JSON data source, it stopped working. Can someone help me figure out why? The only change I ...

Stop md-select dropdown from opening when clicked in specific scenario

I currently have a situation where I want to prevent the md-select from opening under a specific condition and instead display a warning dialog. One way I can achieve this is by disabling the md-select using the following code: ng-disabled="controller.un ...

I'm encountering a typescript error as I migrate a Paho MQTT function from Angular 1 to Angular 2 - what could be causing this issue?

When connecting to my MQTT broker, I am working on several tasks. In my Ionic 2 and Angular 2 application, I have created an MQTT provider. Here is the provider code: import { Component } from '@angular/core'; import { NavController, ViewControl ...

How can I implement Jquery ajax calls in various JavaScript functions?

I'm encountering an issue with a particular function in my code function readComm(){ $.post("something.php", {read:"read"}, function(data){ retVal = $.trim(data).toString(); console.log(retVal); return retVal; }); } T ...

Evaluating TypeError in CoffeeScript using Jasmine with Backbone.js

Currently, I am following the PeepCode video tutorial on Backbone.js, but I am rewriting all the code in CoffeeScript instead of plain JavaScript. Everything is going well so far, except when I attempt to run Jasmine tests on the code, I encounter some Ty ...

What is the process of sending data to another JSP page via AJAX when submitting data to a link within a JSP page?

I am facing an issue with forwarding data from a URL link in a JSP form page to another JSP page after submitting the form. How can I achieve this successfully? index.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> ...

Automatically submitting a form in React.js based on certain conditions being met

Does anyone have experience with React login and register form buttons that trigger Redux actions? I'm facing an issue where both actions are being dispatched at the same time when certain conditions are met. Here is my code snippet: const LoginPage ...

When using jQuery AJAX, the script is returning blank values

Facing a frustrating issue here. I'm sending an AJAX request to a PHP file, but when I check Chrome Network Tools, it doesn't return any JSON data. However, when I try posting the same data using POSTMAN in Chrome, it returns correctly. Also, if ...