Peter Wilson Peter Wilson - 5 months ago 14
AngularJS Question

Binding dynamically created input inside ng-repeat

I am working on an AngularJs app, in on of views I have an array like this in my controller

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


I am working on an editing form for this emails so my view is looks like

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

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


Finally I have a button which on click add another field to add new email and the function is looks like

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


Now my array is looks like

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


The issue is when the new input appears and when I am typing anything in it the $scope.emails dose'nt get updated and the most wired thing is the last object become an empty objet so my array now looks like

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


any help will be appreciated, thanks in advance!

Answer

I think the problem is because the input type email. The angular only bind valid input values. So, until you insert a valid e-mail, your object should be empty. Only after you finish typing the bind will work. See the snippet:

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