Reset ng-model value from controller after ng-change Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Reset ng-model value from controller after ng-change without wasting too much if your time.

The question is published on by Tutorial Guruji team.

How can I reset the value of an ng-model in the controller after an ngChange without using 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 in the controller is as follows

$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 wouldn’t want to implement a directive just for this single occurence

Answer

You should Ideally store old value of items inside scope & do use them later to revert back to original one.

$scope.loadItem = function(){
    $http.get('/api/getitems').then(function(response){
        $scope.items = response.data;
        $scope.oldCopy = angular.copy($scope.items); //do it where ever you are setting items
    });
}

Then do send whole item to ng-change method 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('Date saved successfully.');
            $scope.loadItem(); //to update items from DB, to make sure items would be updated.
        })
    }
    else{
        //get current old object based on itemId, & then do revert it.
        var oldItem = $filter('filter')($scope.oldCopy, {itemId: item.itemId}, true)
        if(oldItem && oldItem.length){
            item = oldItem[0]; //filters return array, so take 1st one while replacing it.
        }
    }
}
We are here to answer your question about Reset ng-model value from controller after ng-change - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji