Ranjith M
Ranjith M

Reputation: 529

Filter ng-repeat results using an id variable stored in controller

I have an id in my controller, let's say id = 1, and a list of data items $scope.items = data. The data structure looks like this :

"data": [ {
         "id":1,
         "name":"ranjith"
     },
     {
        "id":2,
        "name":"sumanth"
     }
]

My HTML

<span ng-repeat="item in items | filter: getResult">{{item.name}}</span>

getResult in my controller:

$scope.getResult = function(a){ if (a.id== $scope.id) return true; else return false; }

I want to output only the item with id=1 means the data set with id=1 and name=ranjith. I tried some codes but nothing seems to work.

Upvotes: 0

Views: 759

Answers (2)

Maen
Maen

Reputation: 10698

You are close to getting it working, but there are several errors:

  • You didn't close your span properly,
  • You didn't output anything in your span, so you won't see a thing if it works
  • You store your dataset in a var called data, and then use items in your ng-repeat

Your code should at least look like this :

var app = angular.module("fiddle", []);

app.controller("fiddle_controller",   function($scope){
  $scope.items = [
    {
         "id":1,
         "name":"ranjith"
    },
    {
        "id":2,
        "name":"sumanth"
    }
  ];
  $scope.id = 1;

  $scope.getResult = function(item){
      return item.id == $scope.id;
  };
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="fiddle">
  <div ng-controller="fiddle_controller">
    <span ng-repeat="item in items | filter: getResult">
      {{item.name}}
    </span>
  </div>
</div>

Upvotes: 2

zamarrowski
zamarrowski

Reputation: 483

Try this:

In html:

<span ng-repeat="item in data | filter: getResult">{{item}}</span>

In controller:

$scope.data =  [ { "id":1, "name":"ranjith" }, { "id":2, "name":"sumanth" } ];
$scope.id = 1;
//Filter
$scope.getResult = function(item){
    return item.id == $scope.id;
};

Upvotes: 1

Related Questions