如何将项目添加到重复列表和停止列表项目中,这些项目正由数据绑定更改

How To Add Item To ng-repeat list and stop list item being changed by databinding

本文关键字:项目 列表 数据绑定 添加      更新时间:2023-09-26

我需要根据使用html输入键入和提交的值构建一个ng重复列表。它是有效的,我可以使用ng重复从输入中返回项目,但当编辑下一个项目的输入时,输入值仍然绑定到ng重复中的值,然后更改该值,而不是添加一个全新的值。我确信我错过了一些简单的东西,但却停留在当下。

如何在每次点击时添加未绑定到输入的新项目?

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);  
    }
}

我意识到我的表达式使用的是输入模型。

{{newitem1}}

代替

{{item.newitem1}}

固定