在 ng-repeat 中绑定动态创建的输入

Binding dynamically created input inside ng-repeat

我正在开发一个 AngularJs 应用程序,在其中一个视图中,我的控制器中有一个这样的数组

$scope.emails = [{email:peter@w34.co},
{email:john@w34.co},
{email:doe@w34.co}
]

我正在编辑这封电子邮件的表格,所以我的视图看起来像

<div ng-repeat='email in emails'>

  <input type='email' ng-model='email.email'>
</div>

最后我有一个按钮,单击它可以添加另一个字段以添加新电子邮件,功能如下所示

$scope.emails.push({email:''});

现在我的数组看起来像

[{email:'peter@w34.co'},
{email:'john@w34.co'},
{email:'doe@w34.co'},
{email:''}
]

问题是当新输入出现时,当我在其中输入任何内容时,$scope.emails dose'nt 得到更新,最有线的是最后一个对象变成空对象,所以我的数组现在看起来像

[{email:peter@w34.co},
{email:john@w34.co},
{email:doe@w34.co},
{}
]

任何帮助将不胜感激,提前致谢!

我认为问题是因为输入类型的电子邮件。 angular 只绑定有效的输入值。因此,在您插入有效的电子邮件之前,您的对象应该是空的。只有在您完成输入后,绑定才会起作用。查看代码段:

'use strict'

var $scope = {};

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

myApp.controller('myCtrl', ['$scope', function($scope){

  $scope.appName = "Name of the application";
  
  $scope.emails = [
    {email:'peter@w34.co'},
    {email:'john@w34.co'},
    {email:'doe@w34.co'}
  ];
  
  $scope.addMail = function(){
    $scope.emails.push({email:''});
  };
  
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">

  {{appName}}

  <hr>
  
  <div ng-repeat='email in emails'>
    <input type='email' ng-model='email.email'>
  </div>
  
  <hr>
  
  <button type="button" ng-click="addMail()">Add new mail</button>
  
  <hr>
  
  {{emails}}
  
</div>