我正在尝试编辑表单输入文本字段。因此,该值是从 API 加载的,然后如果您按下编辑按钮,您可以更改该值并取消更改或更新为您刚刚输入的新值。我尝试将预先编辑的值存储在局部变量中,以便能够取消更改。这是我在 Controller 中的代码。
$scope.preEditFirstName = {};
$scope.edit = function(model) {
// Copy preedited data locally
$scope.preEditFirstName = angular.copy(model);
}
$scope.cancelEdit = function(model){
$scope.model = angular.copy($scope.preEditFirstName);
console.log($scope.model); //Correct result!
};
这是 View
<div ng-show="beforeFirstNameEdit">
{{accountData.firstname || "Loading..."}}
</div>
<div ng-show="!beforeFirstNameEdit">
<input name="firstName" ng-model="accountData.firstname" placeholder="First Name" type="text" />
</div>
<div ng-show="beforeFirstNameEdit">
<button type="button" ng-click="beforeFirstNameEdit = false; edit(accountData.firstname)">Edit</button>
</div>
<div ng-show="!beforeFirstNameEdit">
<button type="button" ng-click="beforeFirstNameEdit = true; update(accountData.firstname)">Save</button>
<button type="button" ng-click="beforeFirstNameEdit = true; cancelEdit(accountData.firstname)">Cancel</button>
</div>
起初您只会看到一个“编辑”按钮,当您按下它时,会出现保存和取消按钮。因此,即使局部变量已正确保存,当我按下取消按钮时,该字段也不会显示其预编辑文本。我该如何解决这个问题?
最佳答案
在 cancelEdit 中使用 $scope.accountData.firstname
而不是 $scope.model
为了使其可重用: 查看:
<button type="button" ng-click="beforeFirstNameEdit = true; cancelEdit('firstname')">Cancel</button>
Controller :
$scope.cancelEdit = function(model){
$scope.accountData[model] = angular.copy($scope.preEditFirstName);
};
现在 cancelEdit 将适用于以 accountData 开头的所有模型。*
关于javascript - AngularJs 中的可编辑输入文本字段不会重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35106988/