【问题标题】:AngularJS add/remove function with ng-repeat and ng-modelAngularJS 使用 ng-repeat 和 ng-model 添加/删除函数
【发布时间】:2016-12-15 21:35:19
【问题描述】:

我正在创建一个具有添加/删除功能的表单。为此,我尝试在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 中制作了我的代码示例。

【问题讨论】:

  • 仅供参考,您不需要按索引引用数组元素。使用表达式中声明的 x 变量。这是你在每次迭代中对特定元素的钩子。

标签: javascript angularjs ng-repeat angularjs-ng-model


【解决方案1】:

所以基本上你每次都会推送一个“项目”引用列表,所以你最终会得到一个对一个项目的多个引用的列表。

你可以这样做:

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的看法。为了简单起见,很多人都这样重复:

<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>

【讨论】:

    【解决方案2】:

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

    快速解决方法是在$scope.add() 中推送项目的副本,而不是项目本身:

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

    更好的方法是将item 作为一个对象,您可以对其进行实例化:

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

    然后

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

    【讨论】:

    • 谢谢!我非常感谢您对参考的解释!我真的帮助了这个问题并更多地理解了这个概念!
    【解决方案3】:

    把你的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 = "";
      };
    }]);
    

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

    之后,当您在数组中添加项目时,请确保重置它们。

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

    检查here

    【讨论】:

    • 没有任何变化
    • @Supergentle 你改了html里的模型了吗?
    • 谢谢我用别人的方法解决了问题。但是,我看到它在您的代码笔中有效。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    • 2016-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多