【问题标题】:Dynamically added item to ng-repeat hold duplicate model将项目动态添加到 ng-repeat 保留重复模型
【发布时间】:2016-01-29 15:57:09
【问题描述】:

我正在创建一个网页,我在其中为用户提供动态添加订单项的选项。我使用了 angularjs 框架(v 1.4.7)。我能够实现将项目动态添加到 ng-repeat 的效果,但模态在动态添加的项目中似乎不是唯一的。

这是显示问题的演示代码:

<div>
<form novalidate class="form-vertical" ng-show="!loading" name="detailsForm" ng-controller="DetailsCtrl">

  <div ng-repeat="social in socials track by $index">
      <ng-form name="urlForm">
            <input type="email" name="socialUrl" ng-model="social.email">
            <span class="alert error" ng-show="urlForm.socialUrl.$error.email">Email error</span>
      </ng-form>
  </div>  
  <a title="Add" class="btn btn-success" href="javascript:void(null)" ng-click="addSocial()"><i class="fa fa-plus fa-lg"></i> Add</a>
</form>
</div>

var myApp = angular.module('myApp', []);

myApp.controller('DetailsCtrl', ['$scope', function($scope) {
    $scope.loading = false;
    var social = {"email":""};

    $scope.socials = [
            { email: 'test@test.com'},
        { email: 'invalid email'}];


  $scope.addSocial = function(){
    $scope.socials.push(social);
  };

    }]
    );

我创建了 fiddle 来显示问题。在小提琴中,请添加一个新项目“12345@email.com”。添加另一个项目“54321@email.com”。您会注意到,在输入第二个时,第一次添加的项目也发生了变化。

Fiddle

【问题讨论】:

    标签: angularjs angularjs-ng-repeat


    【解决方案1】:

    这是因为您将相同的对象添加到数组中,然后您没有将社交分配给新对象。这种方式角度保持它的绑定。

    Here's your fix:

    $scope.addSocial = function(){
        $scope.socials.push(social);
        social = {"email": ""};
      };
    

    【讨论】:

    • 非常感谢@Voreny。你让我开心:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多