Leveraging the power of resolve in AngularJS $modal to synchronize with RESTful responses

I have been dealing with some older code that utilizes angularjs 1.x for a web frontend. I am in the process of creating a modal dialog that needs to make a RESTful call to the backend upon opening and wait for the data to be returned before displaying the view.

Most of the steps were clear to me, but there is one aspect that is confusing me. I initially thought I needed to use 'resolve' to define a function that would return a $promise to the controller. However, when I checked inside my controller using a breakpoint, I discovered that the parameter is an object containing the promise, resolution status, and then the actual data.

Although I can extract the necessary data from this object, it seems unnecessary. My focus in the controller is solely on the data that is returned, not the promise itself. Is there a way to structure this so that only the data is passed to the controller, or is this simply how angular modals are designed to work?

A snippet of the code I am working with:

$scope.openTerritorySelect = function () {

                var modalInstance = $modal.open({
                    animation: true,
                    templateUrl: 'prospect/detail/selectTerritoriesModal.tpl.html',
                    controller: function($scope, $modalInstance, availableReps){

                        $scope.reps = availableReps;
                        $scope.ok=function()
                        {
                            $modalInstance.close();
                        };

                        $scope.cancel=function()
                        {
                            $modalInstance.dismiss('cancel');
                        };
                    },
                    resolve: {
                        availableReps: function () {
                           return Prospect.getRelatedReps({}, function (data, header) {
                                $scope.busy = false;
                                return data.result;

                            }, function (response) {
                                $scope.busy = false;

                                if (response.status === 404) {
                                    $rootScope.navError = "Could not get reps";
                                    $location.path("/naverror");
                                }

                            }).$promise;

                        }
                    }

                });

                modalInstance.result.then(function (selectedReps) {

                }, function () {
                    console.log('Modal dismissed at: ' + new Date());
                });
            };

The 'Prospect' service class:

angular.module('customer.prospect', [ "ngResource" ]).factory('Prospect', [ 'contextRoute', '$resource', function(contextRoute, $resource) {
    return {

        getRelatedReps : function(args, success, fail) {

            return this.payload.getRelatedReps(args, success, fail);
        },

        payload : $resource(contextRoute + '/api/v1/prospects/:id', {

        }, {

            'getRelatedReps' : {
                url : contextRoute + '/api/v1/prospects/territories/reps',
                method : 'GET',
                isArray : false
            }
        })
    };

} ]);

Answer №1

To streamline the process, consider initiating the REST request prior to opening the modal. If the request fails, would you still want to proceed with opening the modal?

$scope.openTerritorySelect = function () {
  Prospect.getRelatedReps({}, function (data, header) {
    $scope.busy = false;
    var modalInstance = $modal.open({
      animation: true,
      templateUrl: 'prospect/detail/selectTerritoriesModal.tpl.html',
      controller: function($scope, $modalInstance, availableReps){
        $scope.reps = availableReps;
         $scope.ok = function() {
           $modalInstance.close();
         };
         $scope.cancel = function() {
           $modalInstance.dismiss('cancel');
         };
       },
       resolve: {
         availableReps: function () {
           return data.result;
       }
    });

    modalInstance.result.then(function (selectedReps) {}, 
      function () {
        console.log('Modal dismissed at: ' + new Date());
      });
  }, function (response) {
    $scope.busy = false;

    if (response.status === 404) {
      $rootScope.navError = "Could not get reps";
      $location.path("/naverror");
    }

 });
};

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

Require transforming JSON formats

Hello, I am facing some challenges when it comes to working with JSON. Using an AJAX request, I am attempting to retrieve a large JSON string from the following link: my JSON The AJAX code is as follows: var $xhr; function loadContent(href){ var hr ...

Hover over the div to center an SVG inside it

Simply put, I am working on a design where a gradient bar moves above a specific element when hovered, creating a visual effect of a triangle. I am now looking for a way to center an SVG inside the element on hover, to create a similar triangular gradient ...

If you refer to a function, are you personally calling the function or asking the reference to call it?

From what I understand, and please correct me if I'm mistaken, when a variable is assigned to a function in the form of a function expression, it doesn't hold the function in the same way that it holds a primitive value. The variable simply refer ...

The coverflow of Swiper is not displaying properly within a Div container

Just to clarify, I am not very experienced and do not know many best practices. I am learning as I go along with projects. I am using Swiper for a game list slider, but when I place it inside another Div, it disappears completely. I can position and size ...

Tips for transferring information using "controller" rather than "app.js" in Node.js

I am currently developing an application using Node.js (Express.js). I am encountering an issue where the form data is not being sent to the controller. The error message "TypeError: Cannot read property 'name' of undefined in Node.js" is appeari ...

Just beginning my journey with node.js and looking for guidance on implementing an npm module into my front-end vanilla JavaScript project

Starting off, I must admit that my knowledge of node.js and web development is quite limited. Despite searching through stackoverflow and Google for a solution, I've come up empty-handed. My main concern is figuring out the necessary steps to take sin ...

Hide and show submenus with jQuery while ensuring that the initial submenu remains visible, along with the main menu

I am struggling to figure out how to make the first message active by default along with its corresponding menu selection in my navbar. I have implemented a show/hide functionality on the main menu click, but currently only the menu is being set as active ...

The filtering feature in AngularJS ng-options is not functioning correctly

Greetings, I am a newcomer to angular. In my current demo application, I have created a list of users with a select filter using ng-option. There seems to be a bug that I have been unable to identify. The issue: When I select the Female option, i ...

Empty body detected in Jquery AJAX request with Django REST running in a Docker environment

Using JavaScript to load a template called index.html from the /static directory. The JavaScript code in app.js: var obj = new Object(); obj.startTime = "123"; obj.endTime = "456"; console.log("fetchNext "+JSON.stringify(obj)); v ...

Create a left-aligned div that spans the entire width of the screen, adjusting its width based on the screen size and positioning it slightly

I have a parent container with two child elements inside. I want the first child to align to the left side and the second child to align to the right side, but not starting from the exact center point. They should be positioned slightly off-center by -100p ...

The png image is not displaying in the browser when using background-image with Webpack

I'm currently working with Webpack and attempting to display a png image in my Firefox browser. The issue I'm facing is that when Webpack compiles, it generates two images in the dist folder. One of these images seems to have an error as it won&a ...

Using createStyles in TypeScript to align content with justifyContent

Within my toolbar, I have two icons positioned on the left end. At the moment, I am applying this specific styling approach: const useStyles = makeStyles((theme: Theme) => createStyles({ root: { display: 'flex', }, appBar: ...

Combine and calculate the total of several columns using the Loadash library

In my Vue application, I am faced with the challenge of grouping an array by date and then calculating sums for multiple columns. The current method I have only allows me to group and sum one column: receiptsByDate: function(){ let byDate = _.groupBy(t ...

Exploring the potential of Raygun.io with Angular Universal

We are currently integrating Raygun.io APM into our Angular 8 app that utilizes Angular Universal. Raygun.io offers a client side javascript library, but to use it with Angular Universal, we need to create a DOM window API. This can be achieved by install ...

Version 2.7.2 of Chart.js now allows users to retrieve the value of a data point by

I need to retrieve the value for each point clicked on, but I am currently only able to get the value of the first line when I click on a point. The GetElementsAtEvent function provides me with an array of 3 active elements, but how can I specifically extr ...

"Troubleshooting a REST API connection issue: MongoNetworkError - unable to establish connection with

I am currently working on setting up a basic REST API for a MongoDB Within my server.js file, I have the following code: const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-P ...

The options in the form select dropdown are not correctly positioned

I am new to using Jquery. I am attempting to create a submit form with a select option in it. However, the drop-down options are not displaying correctly. They appear slightly above and to the left of where they should be.https://i.sstatic.net/xZecM.png I ...

Trouble arises when dynamic parameters fail to function post building in Nuxt

In my Nuxt project set to "spa" mode, I am facing an issue with a URL containing a dynamic parameter /shop/:product, which could have various values such as: /shop/ipad-128gb-rose-gold /shop/subway-gift-card /shop/any-string and so on. This ...

Utilizing the power of Vuetify.js for a sleek top-right menu

I'm diving into Vue and looking to create a horizontal top-right menu with Vuetify. However, I'm getting a vertical menu instead of the desired horizontal layout. The Vuetify documentation doesn't offer a clear example of how to implement th ...

Utilizing Axios in Vue.js to extract tokens from a URL and initiate a POST request

Recently, I've been working on extracting a token from a URL like http://test.com/confirm?token=MMsndiwhjidh... and then sending a post request to another server. This is the approach I took: export default { data() { return { ...