Clearing the ng-model value in a controller following an ng-change event

Is there a way to reset the ng-model value in the controller after an ngChange event without needing to use a directive?

<div ng-repeat="i in items">
    <!-- Some DOM comes here -->

    <select ng-model="i.avail" ng-change="changeAvail(i.id, i.avail)">
        <option value="true">Available</option>
        <option value="false">Unavailable</option>
    </select>

    <!-- More DOM follows -->
</div>

The JavaScript code in the controller is shown below:

$scope.changeAvail = function(itemId, value){
    if(confirm("You cannot undo this action")){
        //Send an ajax request to backend for an irreversible action
    }
    else{
        //Restore input to initial value;
    }
}

I prefer not to create a custom directive just for this specific scenario

Answer №1

It is recommended to store the previous values of items within the scope and use them later to revert back to the original state.

$scope.loadItem = function(){
    $http.get('/api/getitems').then(function(response){
        $scope.items = response.data;
        $scope.oldCopy = angular.copy($scope.items); // Store old values when setting items
    });
}

When triggering the ng-change method, pass the entire item like ng-change="changeAvail(i)"

$scope.changeAvail = function(item){
    if(confirm("You cannot undo this action")){
        // Save object
        $http.post('/api/data/save', item).then(function(){
            //alert('Data saved successfully.');
            $scope.loadItem(); // Update items from DB to ensure they are current.
        })
    }
    else{
        // Retrieve the previous object based on itemId and revert back to it.
        var oldItem = $filter('filter')($scope.oldCopy, {itemId: item.itemId}, true)
        if(oldItem && oldItem.length){
            item = oldItem[0]; // Replace with the first item in the array returned by filters.
        }
    }
}

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

How can I retrieve a global variable in Angular that was initialized within an IIFE?

I'm a beginner in Angular, so I ask for your patience. Currently, I am in the process of migrating an app from Asp.net MVC5 to Angular. One of the key functionalities of this application involves connecting to a third-party system by downloading a Jav ...

Rendering images from Laravel's storage folder in a React component

When uploading an image from a React frontend to a Laravel backend, I encountered an issue where the uploaded image path was saved in the database but the image wouldn't display. React code ` useEffect(() => { axiosClient .g ...

Using .change(); in JavaScript code with jQuery does not trigger a function

Here we have a generic code example for a jQuery function: $(document).ready(function() { if (something) { // This does something } else if (something else) { // This does something else } else { // And this does somethin ...

There seems to be a limitation in JS/JQuery where it is unable to append HTML that spans

I am encountering an issue with retrieving data in a div element. It seems that the function provided does not work correctly for files larger than a single line of code or even possibly a string. What can be done to resolve this? <ul class="dropdo ...

What is the best way to prevent a draggable div from moving past the edge of the viewport?

My situation involves a draggable div that functions as a popup window when a specific button is clicked. However, I noticed that dragging the div to the end of the viewport allows me to drag it out of the visible area, causing the body of the page to expa ...

Endless scrolling feature malfunctioning

On my profile_page.php, the default setting is to display 10 posts (10 rows from the database) for the user. If a user has more than 10 posts, and scrolls to the bottom of the page, the div should expand to reveal the remaining posts (maximum of 10). For e ...

What is the best way to invoke a function in a class from a different class in Angular 6?

Below is the code snippet: import { Component, OnInit, ViewChild } from '@angular/core'; import { AuthService } from '../core/auth.service'; import { MatRadioButton, MatPaginator, MatSort, MatTableDataSource } from '@angular/mater ...

Is there a way to display my array within my React component using JavaScript?

I am working with an element that looks like this: const DropdownElements = [ { key: 1, title: "City", placeholder: "Select City", apiUrl: "https://api.npoint.io/995de746afde6410e3bd", type: "city&qu ...

Is it possible to automatically adjust the cursor position in a textarea when the language is switched?

I am working with a textarea that needs to support both English and Arabic languages. In English, text is typically left-aligned, so the cursor should start on the left-hand side. However, in Arabic, text is right-aligned, meaning the cursor should begin ...

In a Vue serverless web application, OpenLayers Map object fails to trigger events

In my Vue serverless web application, I have implemented an OpenLayers map initialized in the mounted lifecycle method. The map is populated with ImageWMS layers that are updated by various functions. After updating the parameters of these layers, I call ...

Is there a way to enlarge images when hovered using canvas?

I came across a fascinating example at the following link: , where the images expand when hovered over. I am aware that this can be achieved using jquery, but I have concerns about its speed and reliability. I would like to experiment with d3.js, although ...

The React.js component search test encounters errors in locating components

I have been working on a React app that utilizes Redux and React-router. I am currently writing tests using React TestUtils, and I encountered an issue with the following test results: The first expect statement is successful: expect(nav).to.have.length(1) ...

Waves emanating from the heart of rings

I'm experimenting with creating a ripple effect using Anime.js on an array of dots forming circles. Despite trying various methods, I can't seem to achieve the desired result. Does anyone have any suggestions on how I can make it work? Here&apos ...

Vue.js Contact Form Issue: Error message - 'Trying to access 'post' property of an undefined object'

Currently, I am encountering the error 'cannot read property 'post' of undefined' in my code, but pinpointing the exact mistake is proving to be a challenge. Given that I am relatively new to Vue JS, I would greatly appreciate it if som ...

Locating the save directory with fileSystem API

I've been working on saving a file using the fileSystem API. It appears that the code below is functional. However, I am unable to locate where the saved file is stored. If it's on MacOS, shouldn't it be in this directory? /Users/USERNAM ...

react-datepicker displaying error message "Preventing default action not possible within a passive event listener invocation"

I've integrated the react-datepicker library in portal mode. While it functions well on browsers, I encounter an error when using mobile browser mode. An issue arises stating: "Unable to preventDefault inside passive event listener invocation" Des ...

Creating a response in Node JS

I'm struggling with crafting a response to the server. Currently, I have a login form that sends data to the server. On the backend, I verify if this data matches the information in a .json file and aim to send a response upon successful validation. ...

Implementing the Delete feature using AJAX in this specific scenario: What is the best approach?

My website utilizes PHP, Smarty, MySQL, jQuery, and other technologies. It involves fetching a large amount of data from the database and presenting matching question ids on a webpage. This process of retrieving and displaying the matching question ids for ...

Navigating through a JavaScript object array within another object

I am looking to iterate through a JavaScript object array Here is my object response: { "kind": "calendar#events", "etag": "\"p3288namrojte20g\"", "summary": "pedicura", "updated": "2019-05-01T14:25:51.642Z", "timeZone": "America/Argentina ...

Unexpected behavior when trying to bind data with AngularJS through a response message

Here is the code snippet: var myApp = angular.module("gameModule", []); myApp.controller("gamecontroller", function ($scope) { $scope.message = "test"; // websocket connection. var gameHub = $.connection.socketHub; $.connection.hub.star ...