gpt4 book ai didi

javascript - 在 ng-change 之后从 Controller 重置 ng-model 值

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:14:15 25 4
gpt4 key购买 nike

如何在不使用指令的情况下在 ngChange 之后重置 Controller 中 ng-model 的值

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

controller中的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.
}
}
}

关于javascript - 在 ng-change 之后从 Controller 重置 ng-model 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36436928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com