can not add new element using ng-repeat in Angular.js

By : subhra
Source: Stackoverflow.com
Question!

I need one help. I need to create extra input element using ng-repeat in angular.js. I did something but its not working. I explaining my code below.

<div>
        <ul>
            <li ng-repeat="r in arr">
                <input type="text" ng-model="r.uname"> 
            </li>
        </ul>
    </div>
<button type="button" id="btn" ng-click="create();">Add</button>

Here I need when user will click on add button the new input field will create just below the first one. My scripting side code is given below.

<script type="text/javascript">
        function ContactController($scope){
            $scope.arr=[{uname:null}];
            $scope.create=function(){
                console.log('hii');
                 $scope.arr.push({
                     uname:null
                 });
                 console.log('hi',$scope.arr);
            }
        }
    </script>

But here i am unable to generate the new input type element. Please help me.

By : subhra


Answers

Define your array like this..

$scope.arr=[{}];
$scope.create=function(){
  $scope.arr.push({});
  console.log('hi',$scope.arr);
}

everything else looks fine..



Please refer to this.

Use track by in order to achieve the thing you're aiming for:

By : ThinhIT


the first thing u are pushing the same element in the array so you want to track the in the ng-repeat

    
By : RandyPrad


This video can help you solving your question :)
By: admin