我正在尝试编辑表单输入文本字段。因此,该值从API加载,然后如果您按下编辑按钮,您可以更改该值并取消更改或使用刚刚输入的新值进行更新。我尝试将预编辑的值存储在局部变量中,以便我可以取消更改。这是我在控制器中的代码。
$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!
};
这是视图
<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>
首先,您只看到一个“编辑”按钮,当您按下它时,会出现按钮保存和取消。因此,即使正确保存了局部变量,当我按下取消按钮时,该字段也不会显示其预编辑文本。我该如何解决这个问题?
答案 0 :(得分:1)
在cancelEdit中使用$scope.accountData.firstname
代替$scope.model
使其可重复使用: 视图:
<button type="button" ng-click="beforeFirstNameEdit = true; cancelEdit('firstname')">Cancel</button>
控制器:
$scope.cancelEdit = function(model){
$scope.accountData[model] = angular.copy($scope.preEditFirstName);
};
所以现在,cancelEdit适用于以accountData开头的所有模型。*