What is the best way to refresh $scope beyond the confines of the modal bootstrap in AngularJS?

Within my $scope.users, I have a list of items that are displayed.

Upon clicking on one of these items, a modal window pops up to confirm deletion. The deletion query functions correctly, but the changes are not reflected in the view for $scope.users. This could be due to the fact that $scope.users is not in the same controller.

Is there a solution to update the scope without resorting to using $rootscope?

app.controller('backController', ['$scope', '$http', '$rootScope','MyFunctions', '$location', '$modal',
  function ($scope, $http, $rootScope, MyFunctions, $location, $modal) {
    MyFunctions.getUsers().then(function (data) {
      $scope.users = data;
    });

    $scope.openModalDeleteUser = function (user) {
      $scope.user = user;
      var modalInstance = $modal.open({
        templateUrl: 'template/app/modalDeleteUser.html',
        controller: 'modalDeleteUserController',
        scope: $scope,
      });
    };

}]);


app.controller('modalDeleteUserController', ['$scope', '$modalInstance', 'MyFunctions',
  function ($scope, $modalInstance, MyFunctions) {

    $scope.delete = function(){
      var data = {};
      data['action'] = 'delete_user';     
      MyFunctions.updateData(data).then(function (response){
        MyFunctions.getUsers().then(function (data) {
          $scope.users = data;
          console.log($scope.users); // Data retrieval is successful, but not updated in the view
        });
      });
      $modalInstance.dismiss('cancel');
    }  

    $scope.cancel = function () {
      $modalInstance.dismiss('cancel');
    };
}]);

Answer №1

Give this a shot:

MyFunctions.fetchUsers().then(function (data) {
      $scope.users.length = 0; //clear the existing array
      $scope.users.push.apply($scope.users,data); //add new data array to the current one.
});

Explanation:

Within your modalDeleteUserController, the $scope is actually a child scope of your backController scope. By using $scope.users = data;, you are creating a new property on the child scope instead of updating the parent scope. This solution clears out old data from the inherited property and appends new data to ensure that the parent scope is also updated.

Referencing the documentation:

scope - a specific scope instance used for the modal's content (specifically, the $modal service generates a child scope of the provided scope). Defaults to $rootScope

Another approach involves defining a property to store your data:

app.controller('backController', ['$scope', '$http', '$rootScope','MyFunctions', '$location', '$modal',
  function ($scope, $http, $rootScope, MyFunctions, $location, $modal) {
    $scope.data = {};//establish a property
    MyFunctions.fetchUsers().then(function (data) {
      $scope.data.users = data; //keep users as a sub-property under this property
    });

Afterwards, use $scope.data.users = data; within your modal modalDeleteUserController

Note: Make sure to update your template bindings to include these new .data prefixes.

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

Is there a way to efficiently handle waiting for multiple setXXX calls when using useState()?

Here is the code snippet I'm working with: useEffect(() => { setData1("test"); setData2("test2"); initialize(); },[]); const initialize = () =>{ console.log(data1); console.log(data2); } The issue I&apos ...

Storing Array Using a FOR Loop

Good day! I am currently working on saving the numbers generated by a FOR loop. The initial number and final number are entered, and the result is a range of numbers that we have selected. For example: Initial Number: 1 Final Number: 5 Result: 1 2 3 4 5 ...

What is the best way to mention a user within a response to a command using Discord.js?

How can I get my bot to ping users? https://i.sstatic.net/mbY0h.png I want my bot to notify users when it responds to a command, similar to how I'm responding in the image with @ON, without actually mentioning them in the message. I attempted to se ...

In JavaScript, numbers cannot begin with a zero

var number = 05000; var addNumber = 1; When I try to add number + addNumber, the result seems to be incorrect. var total = number + addNumber; // the result is 20481 Refer to the image below for the quick watch result: https://i.sstatic.net/Hwz84.png ...

I am looking to create a PHP script that restricts access to individuals under the age of 18 based on the current

I'm looking for a way to use Php, javascript, or ajax to restrict access for individuals under 18 years old based on the current date. Any suggestions on how I can achieve this? Could someone please review my code for calculating age onblur or onSubm ...

Decoupling the Angular frontend for UIs from the Yii backend's Controller and Model layers

My goal is to integrate an Angular frontend with a Yii backend in a way that Angular handles routing and views while Yii manages controllers, models, and database connections. Angular will make AJAX requests for data, which will be processed by the RESTful ...

Personalized Map Designs for the Store Finder Plugin on WordPress

I am attempting to customize the appearance of a Google Map using the Store Locator Plus plugin for WordPress. I came across a support thread where someone successfully applied custom styles to the map with the following code snippet: <script> $(win ...

Use React to insert a leading zero next to a number in the input field if the number is greater than 10

I have scoured the web and consulted resources like this one but haven't found a solution that addresses my specific issue with adding padding to input numbers. My goal is to automatically add a leading zero whenever the number inside an input field i ...

How can one effectively develop a component library that is compatible with both React and Preact?

I'm currently in the midst of a project that involves both React and Preact. I've come across a situation where I need to utilize the same component for both React and Preact. Would it be wise to package the component into an npm library? What a ...

Is there a way to retrieve the dates from last month using jQuery?

Currently, I am unable to select past dates with the provided code. How can I adjust it to allow for selecting dates from previous months? let firstDay = new Date(); $('#date_filter_startmonthly').datepicker({ startDate: firstDay, endDate: ...

Using GraphQL to verify the existence of a transaction within the blockchain

Even though I have a transaction ID, there are instances where it may take some time for a monetary transaction to appear on Blockchains. My approach involves using GraphQL to access the blockchain by querying it with the transaction ID. A return of &apos ...

Angular: The Ultimate Guide to Reloading a Specific Section of HTML (Form/Div/Table)

On my create operation page, I have a form with two fields. When I reload the page using window.reload in code, I can see updates in the form. However, I want to trigger a refresh on the form by clicking a button. I need help writing a function that can r ...

Continuously adding html elements every third repetition

Is there a way to easily insert new row divs and wrapper divs after every three iterations in EJS (HTML with JavaScript)? I have a template that requires this structure: <div class="row"> <div class="wrapper"> <div class="c ...

Update the "select" element's "option" value upon redirection from another page

I have a webpage called Page A, where I have three anchor links. Then there is also Page B, where I have a select dropdown with the options 30, 180, and 365. What I want to achieve is that when I click on one of the anchor links on Page A (which have href ...

The results of an AJAX file upload operation

Currently, I am utilizing an AJAX File Uploader from the following link: The code I am using is as follows: function ajaxFileUpload() { $('input[type=file]').each(function () { if ($(this).val() == "") { return true; ...

Tips on integrating alert functionality with ajax form submission

My method of submitting a form involves using ajax, with the following code to confirm the submission and display a message on the same page within HTML: $.ajax({ type: "POST", url: "process.php", da ...

EmeraldSocks Tweenmax motion design

I need help with Tweenmax animation. I'm attempting to animate an id selector, but nothing is happening. Both the selector and content are unresponsive. Can someone assist me? Here is the code: <!DOCTYPE html> <html> <head> ...

Unable to perform an update on node.js

I need to upgrade my node.js to create a new angular project. However, when I try to run this command: npm update -g I encounter the following error message: npm ERR! Windows_NT 6.3.9600 npm ERR! argv "C:\\Program Files (x86)\\nodej ...

To view the contents of the dropdown list on an iPhone, simply tap the arrow key next to the mobile dropdown list and the contents will be

I am attempting to trigger the dropdown list contents to open/show by tapping on the arrow keys near AutoFill on the iPhone mobile keyboard. This action should mimic clicking on the dropdown itself. Currently, I am working on implementing this feature for ...

Console is displaying an error message stating that the $http.post function is returning

Just diving into angular and I've set up a controller to fetch data from a factory that's loaded with an $http.get method connecting to a RESTful API: videoModule.factory('myFactory', function($http){ var factory = {}; facto ...