ng-repeat模型绑定(用于添加动态创建的电子邮件)

时间:2014-11-06 03:24:13

标签: javascript angularjs angularjs-directive angularjs-scope angularjs-ng-repeat

下面的代码显示了List电子邮件的绑定,但我无法将新添加的电子邮件绑定到$ scope.emails(不包含添加的新电子邮件用户)。有什么想法吗?

//电子邮件是服务器端的列表 // email是一个字符串

所以我绑定ng-model = email但是

但是执行以下操作无效

$ scope.contactInformation.Emails.push(电子邮件); - >抱怨重复


<div ng-repeat="email in emails">
    <div class="form-group">
    <label for="email">Email</label>
    <div class="input-group input-group-sm input-group-minimal">
         <span class="input-group-addon">
               <i class="linecons-mail"></i>
         </span>
         <input type="text" class="form-control" ng-model="email" />
     </div>
     <button class="btn btn-primary" ng-show="$last" ng-click="AddEmail()">Add Email</button>

Controller.js

// modelParams.ContactInformation.Emails = new在服务器端检索时的List(字符串)()

$scope.emails = modelParams.ContactInformation.Emails;

$scope.AddEmail = function () {
    $scope.contactInformation.Emails.push({ email: null });
};

1 个答案:

答案 0 :(得分:0)

我正在修改答案以避免混淆......以下是应该如何完成的工作 - 填写空白以适应您的情况。

<强> controller.js

// assuming emails is an array of strings (whether defined locally or from a server)
$scope.emails = ["email1", "email2", ...];

$scope.addEmail = function(){
  $scope.emails.push(""); // push an empty array as new not-yet-set email
}

HTML基本上是正确的。我会移动&#34;添加&#34;按钮到ng-repeat div之外,而不是依赖于$last

<div ng-repeat="email in emails track by $index">
  <input type="text" ng-model="email" />
</div>
<button ng-click="addEmail()">Add Email</button>

修改

上面的示例实际上不起作用,因为ng-model binds to a primitive(字符串)ng-repeat中的email

有两种方法可以修复:

接近1

制作一个对象数组。如果从服务器获得一个字符串数组,则需要转换为一个对象数组,如下所示:

$scope.emails = [];
angular.forEach(arrayOfEmailStrings, function(v, k){ $scope.emails.push({value: v}); });

并且如此访问:

<input type="text" ng-model="email.value" />

接近2

使用$index属性:

<input type="text" ng-model="emails[$index]" />