Search code examples
angularjsangularjs-ng-repeat

ng-repeat : ng-model problem adding new element


I have I form of inputs and using ng-repeat I add new inputs fields dinamically with button. Each input is already completed by "text".

The problem :

When I insert new input field by button, the first input field clean out text.

I verify in my browser debugger and first element of my Items Array is not empty. Why it is not present on input ?

There is my HTML:

<div class="row">
    <div class="col-sm-10">
        <input ng-repeat="item in vm.myItemsArray" 
        name="myItemName" 
        class="form-control" 
        type="text" 
        ng-model="item.value"/>
    </div>
    <div class="col-sm-1 col-sm-offset-1">
        <span ng-click="addItem()" class="glyphicon glyphicon-plus btn-sm btn-default"/>
    </div>
</div>

AND JS :

// INITIALIZE INPUTS
vm.myItemsArray = [{value: "text"}];

// ADD NEW INPUTS
function addItem() {
    vm.myItemsArray.push({value: "text"});
}

Solution

  • (function() {
        'use strict';
        angular
            .module('angularExampleModule',[])
            .controller('angularExampleController', ['$scope', angularExampleController]);
    
        function angularExampleController($scope){
          $scope.myItemsArray = [{value: "text"}];
          $scope.addItem = function () {
          	$scope.myItemsArray.push({value: "text"});
          }
    }
    })();
    .input-element{
      margin:10px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="angularExampleModule" ng-controller="angularExampleController">
    <div class="row">
        <div class="col-sm-10 input-element" ng-repeat="item in myItemsArray">
            <input name="myItemName" class="form-control" type="text" ng-model="item.value"/>
        </div>
        <div class="col-sm-1 col-sm-offset-1">
        <button ng-click="addItem()" class="glyphicon glyphicon-plus btn-sm btn-default">Add Item</button>
     
        </div>
    </div>

    OR Check this https://codepen.io/DeepaliK/pen/BqXqNB