Using Angular.js to trigger a callback function from a separate controller

Currently in my angular project, I am utilizing Angular.js material. I am trying to display a $mdialog with a custom controller, where the user can modify some data and have those changes applied to my $scope variable. This is an example of what I am doing at the moment:

function myControllerFn($scope, MyService){
   // I am making a copy of my service variable to avoid altering it until the user clicks on the save button
   $scope.name = angular.copy(MyService.name); 

   $scope.editCurrentProfile = function() {
       $scope.showEditProfileDialog($scope.name).then(function(name){
                    $scope.name = name;
       }
   }

   $scope.showEditProfileDialog = function(name) {
      var deferred = $q.defer();
      $mdDialog.show({
         controller: 'editProfileViewCtrl',
         templateUrl: 'controllers/editProfileDialog.tmpl.html',
         locals: {
             name: name,
             deferred: deferred
         }
      });
         return deferred.promise;
     };
}

Subsequently, in the dialog controller, I have:

function editProfileViewCtrl($scope, name, deffered) {
    deferred.resolve('newName');
}

However, I believe this method may not be the most efficient. Therefore, what is the optimal way to communicate between two view controllers in angular without the need for a new service? Or would it be better to create another service, such as EditDialogService, where the results can be saved?

Answer №1

Upon opening a modal, the show() method will result in a promise being returned.

$scope.displayEditProfileModal = function(name) {
  var modalInstance = $mdDialog.show({
     controller: 'editProfileViewCtrl',
     templateUrl: 'controllers/editProfileDialog.tmpl.html',
     locals: {
         name: name
     }
  });

   modalInstance.then(function(result){
      // Handle the returned value
      // For example, set the result as the new name
      $scope.name = result;
   }, function(error){
      // This block executes when the modal is cancelled
   });
 }

Your modal controller can utilize $mdDialog by injecting it.

function editProfileViewCtrl($scope, name, $mdDialog) {
    $scope.close = function() {
        $mdDialog.hide('newName');
    }
}

Answer №2

It is recommended to develop a directive with your user as the scope variable. Angular takes care of the data binding process automatically.

Answer №3

Creating a basic controller function that can utilize the $scope is achievable.

$mdDialog.show({
  controller: function () { this.parent = $scope; },
  templateUrl: 'controllers/editProfileDialog.tmpl.html',
  locals: {
     name: name,
     deferred: deferred
  }
});

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

Reposition the element at the bottom of its parent element

I am facing an issue with the HTML structure in my application: <div class="work-item"> <div class="image-container"> </div> <div class="text-container"> </div> </div ...

Trigger a click event in jQuery to activate a form through a hyperlink

I'm facing an issue where I want to implement a password-reset form based on a certain flag being triggered. Currently, my code is set up to prompt the user to change their password if the password_changed_flag is not present. Depending on the user&ap ...

Is it possible to utilize Jsoup to extract specific portions of JavaScript code from a webpage?

I am looking to extract data from the following script: $(document).ready(function(){ $("#areaName").val(1);$("#state").val(29);$("#city").val(1); $("#subareaName").val(1);$("#lane").val(1); } Specifically, I need to retrieve values such as areaName ...

Issues with Angular and Bootstrap: ng-hide functionality not functioning correctly

I am struggling to grasp the concept of the ng-show angular directive as it is not functioning correctly for me. Despite following some examples I found online, I cannot seem to change the boolean value in the controller like they suggest. Instead of using ...

How can you tap into local storage in CSS while utilizing a chrome extension?

Can I access local storage from a Chrome extension's options file using CSS? Is it possible to use JavaScript to define a variable that can be utilized in CSS, or is local storage only accessible through JavaScript? If local storage is restricted to J ...

Steps for displaying the output of a post request in printing

I am currently working on creating a basic search bar functionality for daycares based on user input. I am utilizing a post request to an API and receiving back a list of daycares that match the input. Below is the code snippet: <template> <div ...

Improving Visibility in AngularJS

I am new to using Angular and encountering a simple issue. I have a button that, when clicked, should reveal a grid and some hidden filters. The filters are structured like this: <div ng-show="filtroFilial" style="visibility: hidden" class="col-md-2"&g ...

Navigating through the Express.js routes incorrectly

I currently have 3 different express.js routes set up: app.get('/packages/:name', (req, res) => {...}); app.get('/packages/search/', (req, res) => {...}); app.get('/packages/search/:name', (req, res) => {...}); At t ...

Participating in a scheduled Discord Voice chat session

Currently, I am in the process of developing a bot that is designed to automatically join a voice chat at midnight and play a specific song. I have experimented with the following code snippet: // To make use of the discord.js module const Discord = requ ...

Retrieve all populated fields on the second tier using Node.js and Mongoose

Do you have any insights to share on Node.js and mongoose? I've defined a mongoose schema and when I use findOne(), it returns a document with multiple elements under the "resource" key. Below is an example of how the document looks like: { "met ...

Steps to isolate the "changed" values from two JSON objects

Here is a unique question that involves comparing JSON structures and extracting the differences. A JqTree has been created, where when the user changes its tree structure, both the "old" JSON and "new" JSON structures need to be compared. Only the values ...

The issue of nested form serialization not functioning properly in JQuery has been identified

I am currently in the process of developing a web application. One particular page within this application contains a form, called form1, and I am inserting another page with its own form, form2, inside of form1. Each form contains their own set of values. ...

Is there a way to automatically calculate the sum of two boxes and display the result in a separate

I am working with two boxes: one is called AuthorizedAmount and the other is called LessLaborToDate: <div class="col-md-6"> <div class="form-group"> <label>Authorized Amount</label> <div class="input-group"> & ...

Obtaining [Symbol(Response internals)] through a JSON response

I am currently utilizing the library isomorphic-unfetch to retrieve JSON data from a Rest API. Here is my approach for making the request: const res = await fetch( `url` ); To extract the body, I simply do: const response = await res.j ...

What is the method to reach a named parameter within a function?

Currently, I am building a RESTful web service using Node JS in combination with Backbone JS. Within this service, there is a specific REST method called GET /users/id/:id, where :id represents the user's identification number. The purpose of this met ...

PHP page Not Refreshing Properly Without Ajax

I am in need of assistance. Could someone please provide me with a code that has been thoroughly reviewed and tested for errors to address my issue? The program, 22.php, consists of a form. The desired functionality is for the user to enter information and ...

Invoking a function within a loop

In order to complete this assignment with a pop art theme, I have chosen to incorporate pokeballs into the design. The task at hand involves using two for loops, one for the top row and one for the bottom row, while also creating a function. The main cha ...

What is the best way to refresh templates (html) when deploying a new version of a SPA?

I'm facing an issue with caching of HTML templates in the browser when releasing new versions of my Single Page Application (SPA). My SPA is built with Angular 1.5, ocLazyload, and ui-router. I have set up gulp tasks to implement cache-busting using ...

Creating aesthetically pleasing URLs from data: A simple guide

Can someone help me transform this data into a pretty URL? I am looking for something similar to Appreciate the assistance! :) var x = {data1, data2, data3}; $.ajax({ url: 'https://mywebsite.com/admin/leads/count/', data: x, type: &a ...

AngularJS - Shared service object mistakenly removed in error

When I call the removeQuestion() function for the second time, 2 questions are being deleted instead of one. Any suggestions on what might be causing this issue? Let me know if you require additional code snippets. controller.js crtPromoCtrl.controller(& ...