javascript - AngularJs 中的可编辑输入文本字段不会重置

标签 javascript angularjs

我正在尝试编辑表单输入文本字段。因此,该值是从 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/

相关文章:

javascript - Jquery循环中setTimeout的使用

javascript - 未捕获的语法错误 : Unexpected token ILLEGAL on Toggle

javascript - 这是使用 html 快照和 google fetch 的预期/想要的结果吗?搜索引擎优化/SPA

javascript - Angular if/else 开关

json - ExpressJS/AngularJS : Converting JSON Object to String

angularjs - 如何重新初始化 Angular 指令?

javascript - 如何在 vue 组件中本地使用 VeeValidate 或任何第三方包

javascript - 正则表达式在第一个小数点后添加 0

javascript - 如何在语义 UI 下拉菜单组件中的 React 组件中使用条件

angularjs - 捕获加载空白页面的所有路由 Angular NodeJs