Rakesh
Rakesh

Reputation: 329

Filter first value of array inside ng-repeat in angularjs

How can i filter josn first element of a row inside ng-repeat using angularjs. i am stuck with this.

My sample code is::

<!DOCTYPE html>
<html>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
 <body>
 <div ng-app="myApp" ng-controller="namesCtrl">
  <div>
    <div ng-repeat="x in num| orderBy:'n'">
     <b>{{x.n}}</b>
     <div ng-repeat="y in amt | orderBy:'v'">
       <div ng-if="x.n==y.n">
         <div>{{y.v}}</div>
       </div>
      </div >
    <br />
    </div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.num= [
    {n:'3'},
    {n:'1'},
    {n:'2'},
    ];

$scope.amt= [
    {n:'1',v:'23'},
    {n:'1',v:'24'},
    {n:'1',v:'45'},
    {n:'2',v:'56'},
    {n:'2',v:'67'},
    {n:'2',v:'45'},
    {n:'3',v:'23'},
    {n:'3',v:'67'},
    {n:'3',v:'19'},
    ];

 });
 </script>

 </body>
 </html>

Result is
1
23
24
45

2
45
56
67

3
19
23
67

I am result only. first value.

like:
1
23

2
45

3
19

Please help...

Upvotes: 0

Views: 1408

Answers (2)

Daniel Gomez
Daniel Gomez

Reputation: 1

(...) < /tr> < /thead> < tbody> < tr ng-repeat="object in objects | SOME_FILTER"> (...) {{object.get("element")}} {{(object.get("element2")).innerElement}} (...) < /tr> < /tbody> < /table> (...)

The 3 dots means that there was some code cut out. "element2" is the one with a JSON inside. "innerElement" is the key. it worked for me, hope would be useful to someone

Upvotes: 0

Slava N.
Slava N.

Reputation: 596

You should create custom filter function:

$scope.myFilter = function (x) {
  return function (y) {
    if (x.n==y.n) {
      return true;
    } else {
      return false;
    }
  }
};

Use it in inner ng-repeat:

 <div ng-repeat="y in amt | orderBy:'v' | filter:myFilter(x) | limitTo:1">
   <div>{{y.v}}</div>
 </div >

Also, to get top 1 result add standard limitTo filter (limitTo:1), wich first argument sets max return count.

Upvotes: 3

Related Questions