ng-repeat get length of array and bind last value of array

523 Views Asked by At
$scope.GetDetails={
  Student:[
      {"id":1,"Name":"Apple","Price":3500}
    ],
  Student:[
      {"id":2,"Name":"Samsung","Price":4000}
     ],
  Student:[
    {"id":3,"Name":"Nokia","Price":1500},
    {"id":3,"Name":"Nokia","Price";7000}
   ]
 }

Am binding data using ng-repeat

 <div ng-repeat="As in GetDetails">
         <div ng-repeat="A in As.Student">
        <span>{{A.Name}}</span> - <span>{{A.Price}}</span>  
    </div>
     </div>

Result is Apple - 3500 Samsung - 4000 Nokia - 1500 Nokia - 7000

Here every thing Ok.But what i want mean , Nokia have two array ,so i have to get name from first array and price from 2nd array Like,

Nokia - 7000,

And Also i need the length of student array.

2

There are 2 best solutions below

0
On

If you want this only for Name: Nokia, then do it like;

<div ng-repeat="A in As.Student">
 <span ng-if="A.Name!=='Nokia'">{{A.Name}}-{{A.Price}}</span>  
 <span ng-if="A.Name==='Nokia' && $last">{{A.Name}}-{{A.Price}}</span>  
</div>

and it you want only last element from every array :

then:

 <div ng-repeat="A in As.Student" ng-if="$last">
        <span>{{A.Name}}</span> - <span>{{A.Price}}</span>  
 </div>
9
On

First, You should change your JSON to achieve your result.

Change JSON to below:

$scope.GetDetails=[
    {Student:[{"id":1,"Name":"Apple","Price":3500}]},
    {Student:[{"id":2,"Name":"Samsung","Price":4000}]},
    {Student:[{"id":3,"Name":"Nokia","Price":1500},{"id":3,"Name":"Nokia","Price":7000}]}
 ]

Please run below code

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

 <div ng-repeat="As in GetDetails">
         <div ng-repeat="A in As.Student" ng-if="$last">
        <span>{{A.Name}}</span> - <span>{{A.Price}}</span>  
    </div>
     </div>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.GetDetails=[
    {Student:[{"id":1,"Name":"Apple","Price":3500}]},
    {Student:[{"id":2,"Name":"Samsung","Price":4000}]},
    {Student:[{"id":3,"Name":"Nokia","Price":1500},{"id":3,"Name":"Nokia","Price":7000}]}
 ]

});
</script>

</body>
</html>

I used ng-if="$last" to take the last value from array

Here is a working DEMO