javascript – 在ng-change之后重置控制器的ng-model值

如何在不使用指令的情况下在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.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.
        }
    }
}
点赞