Akshay Vasu Akshay Vasu -4 years ago 121
AngularJS Question

Angular js is not printing the data of ng-init using ng-repeat

I am a newbie and i am trying few angular js examples but when create 2 div elements and try to run the angular js program for it. the initialized array is getting printed for the second div and it is not getting printed for the first div when i am using ng-repeat. Can anyone tell me why it is happening. I am not able to see any difference between the way 2 arrays have been initialized. The code is below.

<html data-ng-app>
<head>
<title>Angular js</title>
</head>
<body>
<input type="text" data-ng-model="name">{{name}}
<div class="container" data-ng-init="namess=['Hello','There','God','There']">
<h3>Looping with the ng-repeat Directive</h3>
<h4>Data to loop through is initialized using ng-init</h4>
<ul>
<li data-ng-repeat="Personname in namess">{{Personname}}</li>
</ul>
</div>
<div class="container" data-ng-init="names=['Dave','Napur','Heedy','Shriva']">
<h3>Looping with the ng-repeat Directive</h3>
<h4>Data to loop through is initialized using ng-init</h4>
<ul>
<li data-ng-repeat="name in names">{{name}}</li>
</ul>
</div>
</body>
<footer>
<script type="text/javascript" src="angular.min.js"></script>
</footer>
</html>


The result i am getting is as below

Looping with the ng-repeat Directive

Data to loop through is initialized using ng-init

Looping with the ng-repeat Directive

Data to loop through is initialized using ng-init

Dave
Napur
Heedy
Shriva

Answer Source

If you look in your console you will see an error about duplicates on the first ng-repeat. Because you have "There" in your array twice you need to add a track by to your ng-repeat. Try replacing it with this:

<li data-ng-repeat="Personname in namess track by $index">{{Personname}}</li>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download