gurudev265 gurudev265 - 26 days ago 6
JSON Question

I am new to Angularjs, just tried populating multiple json value but it's not working

<div ng-controller="studentController" ng-repeat = "student in students | unique = 'RollNo' " >
<table class="profile-info">
<tr>
<th>Roll No</th>
<td>{{ student.RollNo }}</td>
</tr>
<tr>
<th>Class</th>
<td>{{ student.Class }}</td>
</tr>
<tr>
<th>Section</th>
<td>{{ student.Section }}</td>
</tr>
<tr>
<th>Sports</th>
<td>{{ student.Sports }}</td>
</tr>
<tr>
<th>other Interests</th>
<td>{{ student.otherInterests }}</td>
</tr>
</table>
</div>

<---- Angular Part---->
// Not able to Populate the Json Value using the Follwing Script //

<script>
function studentController($scope,$http) {
var url = "aboutme.json";
$http.get(url).success( function(response) {
$scope.students = response.data;
});
}
</script>

<--- JSON PART --- >
[
{
"Class" : 1,
"RollNo" : 1,
"Section" : "A",
"Sports" : "Football",
"otherInterests" : "Music",
},

{
"Class" : 12,
"RollNo" : 2,
"Section" : "B",
"Sports" : "Counter-Strike",
"otherInterests" : "Music",
}
]

Answer

Some small change you have to made in HTML.So, that ng-repeat will work as per your expextation.

  1. Use ng-repeat on tr of td instead of whole div.
  2. Make sure that $scope.students having the same JSON as shown in the JSON part in the post.

Working demo :

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

myApp.controller('studentController',function($scope) {
  $scope.students = [
   {
      "Class" : 1,
      "RollNo" : 1,
      "Section" : "A",
      "Sports" : "Football",
      "otherInterests" : "Music"
   },
  {
      "Class" : 12,
      "RollNo" : 2,
      "Section" : "B",
      "Sports" : "Counter-Strike",
      "otherInterests" : "Music"
   }
];
})
table,th,td {
  border:1px solid black;
  }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="studentController"> 
<table class="profile-info">
    <tr>
        <th>Roll No</th>
        <th>Class</th>
        <th>Section</th>
        <th>Sports</th>
        <th>other Interests</th>
    </tr>
    <tr ng-repeat="student in students">
        <td>{{ student.RollNo }}</td>              
        <td>{{ student.Class }}</td>   
        <td>{{ student.Section }}</td>   
        <td>{{ student.Sports }}</td>  
        <td>{{ student.otherInterests }}</td>
    </tr>                  
</table>
</div>

Comments