我正在尝试从项目列表中创建可编辑输入列表。我希望用户能够编辑任何项目,但如果他们改变主意,他们可以单击一个按钮并将其重置为原来的样子。
到目前为止,除了重置之外,我的一切正常。
我的html
<div ng-app ng-controller="TestController">
<div ng-repeat="item in list">
<label>Input {{$index+1}}:</label>
<input ng-model="item.value" type="text" ng-click="copy(item)"/>
<button ng-click="reset(item)">
x
</button>
</div>
{{list}}<br>
{{selected_item_backup}}
</div>
我的 Controller
function TestController($scope) {
$scope.selected_item_backup = {};
$scope.list = [ { value: 'value 1' }, { value: 'value 2' }, { value: 'value 3' } ];
$scope.reset = function (item) {
// i know this wont work for many reasons, it is just an example of what I would like to do
item = $scope.selected_item_backup;
};
$scope.copy = function (item) {
angular.copy(item, $scope.selected_item_backup);
};
}
这是一个 fiddle http://jsfiddle.net/ryanmc/1ab24o4t/1/
请记住,这是我的真实代码的简化版本。我的对象每个都有许多可编辑字段。它们也没有索引,因此不能依赖索引。我只想能够在新项目之上分配原始项目并替换它。
最佳答案
这是工作解决方案 jsfiddle
function TestController($scope) {
$scope.list = [{
value: 'value 1'
}, {
value: 'value 2'
}, {
value: 'value 3'
}];
var orgiinalList = [];
angular.forEach($scope.list, function(item) {
orgiinalList.push(angular.copy(item));
});
$scope.reset = function(index) {
$scope.list[index] = angular.copy(orgiinalList[index]);
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="TestController">
<div ng-repeat="item in list">
<label>Input {{$index+1}}:</label>
<input ng-model="item.value" type="text" />
<button ng-click="reset($index)">
x
</button>
</div>
{{list}}
<br>
</div>
关于javascript - 在 ng-repeat 中从 Controller 重置 ng-model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35260975/