Angular to update array after making changes in form using a modal popup

When it comes to editing object details, I rely on the ui bootstrap modal directive. Using the same controller for adding new entities or editing existing ones has worked well so far. However, a problem arises when updating an existing object. The current code pushes the updated object to the array, but not to the database. This results in duplicates of the old and new records in the array. Upon refreshing, the old duplicate disappears as the controller queries the actual array again.

$scope.openSaleDlg = function (saleId) {
    var modalInstance = $modal.open({
        backdrop: 'static',
        templateUrl: '/sales/detail.html',
        controller: 'SaleDetailCtrl',
        scope: $scope,
        resolve: {
            saleId: function () {
                return saleId;
            }
        }
    });

modalInstance.result.then(
    function (sale) {
        $scope.sales.push(sale)
    }
);

};

A potential solution could be to have the .then method execute $scope.sales = Sale.query(); upon success. However, there may be a more efficient way to update the object in the list without querying the database again.

Answer №1

To implement your suggestion, you can update the object in the list if it already exists instead of pushing it. This way, Angular will detect the change and re-render accordingly.

Here is an example of how you could achieve this:

modalInstance.result.then(function (sale) {
  var saleToUpdate = $scope.sales.find(function (existingSale) {
    return existingSale.id == sale.id;
  });

  if (saleToUpdate) {
    angular.extend(saleToUpdate, sale);
  } else {
    $scope.sales.push(sale);
  }
});

Keep in mind that utilizing Array#find may require a polyfill or an alternative approach to searching the array.

Answer №2

One recommendation would be to store the 'sale' index for easy access:

 $scope.showSaleDialog = function (sale) {
    var modalInstance = $modal.open({
        backdrop: 'static',
        templateUrl: '/sales/detail.html',
        controller: 'SaleDetailCtrl',
        scope: $scope,
        resolve: {
            saleId: function () {
                return sale.Id;
            }
        }
    });
    $scope.saleIndex = $scope.sales.indexOf(sale)
    modalInstance.result.then(
        function (sale) {
            if($scope.saleIndex !== -1){
                $scope.sales[$scope.saleIndex] = sale;
            }
            else{
                $scope.sales.push(sale);
            }

        }
    );

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

What is the best way to assign a value to a property in a Controller or Global Variable using jQuery?

On my ASP MVC 5 site, I have a checkbox within the NavBar element. This checkbox's state dictates whether or not the Grid will display Inactive records alongside active ones on each page. In an attempt to have all controllers access the same property ...

React throws a "ReferenceError: indexedDB is not defined" but surprisingly, it still manages to function properly

I utilized yarn to install idb-keyval By utilizing the following code, I imported it: import { set } from 'idb-keyval'; Then, I assigned a value to a variable using the following code snippet: set('hello', 'world'); Althou ...

Numerous Levels of Dropdown Menus

I am looking to implement a feature on a web page where users can select multiple vehicles using JQuery. The idea is that selecting the brand in the first dropdown will populate the second dropdown with the models available for that specific brand. The ...

What are the steps for releasing a Next.js app as an npm package?

Currently, my web application is developed using Next.js. I am interested in distributing it as an npm package for others to utilize in their projects. Despite my efforts to search and seek assistance through Google, I have not come across any valuable ins ...

Emphasize the designated drop zone in Dragula

Incorporating the Dragula package into my Angular 2 project has greatly enhanced the drag-and-drop functionality. Bundling this feature has been a seamless experience. Visit the ng2-dragula GitHub page for more information. Although the drag-and-drop fun ...

JavaScript formula for calculating dates together

I'm currently developing a PHP program for generating invoices. I'm implementing a datetimepicker to select the invoice generation date and due date. Now, I need the due date field to be automatically populated by adding a specific value to the i ...

Tips for effortlessly moving content by dragging and dropping it into a text box

Before attempting to create something, I want to verify its feasibility. Begin with a text area that can be pre-filled with text and allow users to add or delete text. Alongside the text area, there are small elements that can be images or HTML components ...

What is the process for generating a custom Firebase Authentication token in Node.js without using a service account JSON file?

I am looking to generate a custom token without relying on a service account json file. I have attempted the following configuration options: https://firebase.google.com/docs/auth/admin/create-custom-tokens#using_a_service_account_id https://firebase.goog ...

Monitor constantly to determine if an element is within the visible portion of the screen

For a thorough understanding of my query, I feel the need to delve deeper. While I am well-versed in solving this issue with vanilla Javascript that is compatible with typescript, my struggle lies in figuring out how to invoke this function throughout th ...

Transforming JSON data into an interactive table with HTML

After spending four days searching for a solution, I am still unable to figure out my problem. My goal is to convert a JSON string data retrieved from a URL into a dynamic table using JQuery and JavaScript. To achieve this, I need to load the JSON string ...

Using a SAML token on the client side to access a JSON webservice, following successful login into the website

Currently, I am in the process of developing a website that utilizes a SAML token for single sign-on security measures. Within this site, there is a form containing multiple input fields that are responsible for triggering updates and validation across var ...

Issue with Retrieving a particular table from SQL Server using mssql in javascript ('dbo.index')

I am currently experiencing an issue with trying to access a table named dbo.Index from SQL Server in my node js express application. Unfortunately, whenever I attempt to do so, the operation fails and returns no data. Below is the code snippet in questio ...

allocating a pointer to an array within a class

void UpdateStrings(char string1[], char string2[]){ str1= string1[]; str2= string2[]; } private: char str1[20]; char str2[20]; I need help identifying the issue in this code. Any insights would be appreciated! The error I am encounterin ...

Implementing automatic scrolling to the bottom while using ng-repeat in Ionic

I've been dealing with a frustrating issue while working on my mobile chat app using Ionic, Angular, and Firebase. The message exchange functionality is fine, but I can't seem to get the auto-scroll feature to work when new messages are received. ...

Storing JSON information within a variable

I'm currently working on an autocomplete form that automatically populates the location field based on the user's zipcode. Below is the code snippet I've written to retrieve a JSON object containing location information using the provided zi ...

Using multiple selectors in JQuery and Javascript

I have a challenge where I need to execute different actions for specific divs. Here is the code snippet I currently have: $("#pending-cancel-1, #pending-cancel-2").click(function(){ Do something special for pending-cancel-1 and pending-cancel-2... }) ...

Combining byte array values with VBA

This is the specific question I am referencing: PBKDF2 Excel UDF and how to concatenate INT(i) The original poster (OP) did not include the code for his "ConcatenateArrayInPlace" function, which he used in his own solution to the problem. I am attempting ...

Trouble encountered when attempting to override styles in Material UI's TableRow

I am attempting to customize Material UI's default styles in order to create a margin between each TableRow. Despite my efforts, it appears that the override is not being reflected in the user interface. ...

Information does not seem to be linking properly in the angular dropdown menu

I am struggling with trying to create a dropdown using angularjs and bootstrap. I want the dropdown to open a link when any value is clicked, but I can't seem to get the data to populate in the dropdown list. If you can offer any help or advice, it wo ...

Display the returned view following an AJAX request

Currently, I am trying to search for a specific date in the database using ajax to trigger the function. However, I am encountering a 404 error when I should be receiving the desired outcome, and the ajax call is entering an error mode. Here is the snippet ...