我需要根据使用 html 输入输入和提交的值构建 ng-repeat 列表。它有效,我可以使用 ng-repeat 从输入返回该项目,但是当编辑下一个项目的输入时,输入值仍然绑定(bind)到 ng-repeat 中的值,然后更改该值而不是添加全新的。我确信我错过了一些简单的东西,但目前被困住了。
如何在每次 ng-click 上添加未绑定(bind)到输入的新项目?
HTML:
<div ng-controller="MyCtrl">
Hello, {{name}}!
<br/>
<input ng-model='newitem1' />
<input ng-model='newitem2' />
<input ng-model='newitem3' />
<button ng-click='add()'>Add</button>
<br/>
<b>Items Added Below</b>
<div select-last ng-repeat='item in items'>
<div ng-model='item' id='item-{{$index}}' class='input-{{$index}}'>{{newitem1}} {{newitem2}} {{newitem3}}</div>
</div>
Javascript:
var myApp = angular.module('myApp',[]);
myApp.directive('selectLast', function () {
return function (scope, element, attrs) {
if (scope.$last=== true) {
console.log("the last element is here");
}
}
});
function MyCtrl($scope) {
$scope.name = 'Please try entering something and click Add button';
$scope.items = [];
$scope.newitem1 = '';
$scope.newitem2 = '';
$scope.newitem3 = '';
$scope.add = function(){
$scope.items.push($scope.newitem1,$scope.newitem2,$scope.newitem3);
}
}
最佳答案
您可以使用angular.copy()
克隆该项目,因此它是数据的副本,但不是对其的直接引用。
这将允许您不断添加新项目。
function MyCtrl($scope) {
$scope.name = 'Please try entering something and click Add button';
$scope.items = [];
$scope.newitem1 = '';
$scope.newitem2 = '';
$scope.newitem3 = '';
$scope.add = function(){
var item1 = angular.copy($scope.newitem1),
item2 = angular.copy($scope.newitem2),
item3 = angular.copy($scope.newitem3);
$scope.items.push(item1, item2, item3);
}
}
关于javascript - 如何将项目添加到 ng-repeat 列表并停止通过数据绑定(bind)更改列表项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33786304/