Zachary Lordford
Zachary Lordford

Reputation: 146

angular ng-repeat array show only one element

I have an array like this

 $scope.mentors = [ {"name":"Jonathan", "status":0},
                    {"name": "Nathan","status":1},
                    {"name": "Chris","status":1},
                    {"name": "Brian","status":0}];

here my view code

<div ng-repeat="m in mentors">
   <div ng-if="m.status == '1'">
   <div>
     {{m.name}}
   </div>

   </div>
</div>

and my result is : Nathan and Chris

what can I do to just make it show Nathan or Chris it must only show one result only

p/s: already try ng-show="$last" it did not work since Brian status is '0'

Upvotes: 0

Views: 2309

Answers (3)

Marcus H&#246;glund
Marcus H&#246;glund

Reputation: 16801

You can filter the array on statuses and then just take the first by checking against $index

angular.module('app', []).controller('myCtrl',function($scope){
$scope.mentors = [ {"name":"Jonathan", "status":0},
                    {"name": "Nathan","status":1},
                    {"name": "Chris","status":1},
                    {"name": "Brian","status":0}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


<!DOCTYPE html>
<html>
<body ng-app="app">
<div ng-controller="myCtrl">
   <div ng-repeat="m in mentors | filter : {status: 1}">
   <div ng-if="$index == 0">
     <div>
       {{m.name}}
     </div>

   </div>
   </div>

</div>
</body>
</html>

Upvotes: 2

Stathis Papalefkas
Stathis Papalefkas

Reputation: 121

You could use the limitTo and filter

<div ng-repeat="m in mentors | filter: { status : '1'}| limitTo : 1">
  <div>
   {{m.name}}
  </div>
</div>

Upvotes: 2

Weedoze
Weedoze

Reputation: 13943

There is no reason to use ng-repeat if you only need to display 1 item.

You should handle this in your controller. Create a new variable that will hold the mentor that you want to show.

To find Nathan, you can use Array#find(). It will return the first item that matches the condition status === 1

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.mentors = [{
      "name": "Jonathan",
      "status": 0
    },
    {
      "name": "Nathan",
      "status": 1
    },
    {
      "name": "Chris",
      "status": 1
    },
    {
      "name": "Brian",
      "status": 0
    }
  ];
  
  $scope.mentor = $scope.mentors.find(m => m.status === 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <h1>{{mentor.name}}</h1>
</div>

Upvotes: 0

Related Questions