ng更改后,从控制器重置ng模型值

Reset ng-model value from controller after ng-change

本文关键字:ng 模型 控制器      更新时间:2024-01-08

在ngChange之后,如何在不使用指令的情况下重置控制器中ng模型的值

<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>

控制器中的Javascript如下

$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;
    }
}

我不想只为这一次出现的实现指令

理想情况下,您应该将项的旧值存储在scope&以后一定要使用它们来恢复到原来的状态。

$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
    });
}

然后将整个项目发送到ng-change方法,如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.
        }
    }
}