AngularJS add/remove 函数与 ng-repeat 和 ng-model

AngularJS add/remove function with ng-repeat and ng-model

我正在创建一个具有 add/remove 功能的表单。为此,我尝试在 ng-repeat 中使用 ng-model。这是我的代码的样子。

<button ng-click='add()'>Add more</button>
<div ng-repeat='x in array track by $index'>
    <input ng-model='array[$index].name'></input>
    <input ng-model='array[$index].phone'></input>
    <input ng-model='array[$index].email'></input>
</div>

//angular module
$scope.add = function () {
    $scope.array.push(item);
};

但是,所有输入字段都将同步,数组中的所有项目看起来都一样,这是我不打算做的。 此外,我在 codepen.

中制作了我的代码示例

将你的javascript改成这样:

angular.module('myapp', [])
.controller('Ctrl', ['$scope', '$compile',function ($scope, $compile) {
  $scope.array = [];

  var item = {
    name: '',
    phone: '',
    email: '',
  };

  $scope.array.push(item);
  $scope.addItem = function () {
    item.name = $scope.name;
    item.phone = $scope.phone;
    item.email = $scope.email;
    $scope.array.push(item);
    $scope.name = "";
    $scope.phone = "";
    $scope.email = "";
  };
}]);

您将必须存储每个姓名、电子邮件和 phone 是单独的模型。

之后,当您将项目添加到数组中时,请务必重置它们。

同时更改 html 中的模型名称。

检查here

每次按下 item 时,您都在按下对同一对象的引用。因此,在输入字段中进行更改时,您会看到所有数组节点中的更新 - 它们引用相同的 item.

快速修复是在 $scope.add() 中推送项目的副本,而不是项目本身:

$scope.array.push(angular.copy(item));

更好的方法是将item作为一个对象,你可以实例化它:

var Item = function (){
    return {
        name: '',
        phone: '',
        email: ''
    };
};

然后

$scope.array.push(new Item());

所以基本上你每次都将 "item" 引用推送到列表,所以你最终得到一个包含对一个项目的多个引用的列表。

你可以这样做:

angular.module('myapp', [])
.controller('Ctrl', ['$scope', '$compile',function ($scope, $compile) {
  $scope.array = [];
  var item = {
    name: '',
    phone: '',
    email: '',
  };

  $scope.array.push(item);
  $scope.addItem = function () {

    $scope.array.push(
      {
        name : '',
        phone: '',
        email: '',        
      }    
    );

  };
}]);

那就可以了。个人意见给html。为了简单起见,很多人都这样做 ng-repeat:

<div ng-repeat='x in array'>
    <input ng-model='x.name'></input>
    <input ng-model='x.phone'></input>
    <input ng-model='x.email'></input>
</div>