Ash
Ash

Reputation: 183

Using orderBy filter dynamically in AngularJS

Trying to enter ordering criteria from input box and order the content dynamically. The code works fine as it is, but when I try to change:

orderBy:'age'

with

orderBy:'{{criteria}}'

it doesn't work. Here is the code:

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="testApp" ng-controller="testController">
<p>Enter ordering criteria in the input box:</p>
<p><input type="text" ng-model="criteria"></p>
<p>{{criteria}}</p>
  <table class="friend">
    <tr>
      <th>Name</th>
      <th>Phone Number</th>
      <th>Age</th>
    </tr>
    <tr ng-repeat="friend in friends | orderBy:'age'">
      <td>{{friend.name}}</td>
      <td>{{friend.phone}}</td>
      <td>{{friend.age}}</td>
    </tr>
  </table>
</div>
<script>
var app = angular.module('testApp',[]);
app.controller('testController', ['$scope', function($scope) {
  $scope.friends =
      [{name:'John', phone:'555-1212', age:10},
       {name:'Mary', phone:'555-9876', age:19},
       {name:'Mike', phone:'555-4321', age:21},
       {name:'Adam', phone:'555-5678', age:35},
       {name:'Julie', phone:'555-8765', age:29}];
}]);
</script>
</body>
</html>

Upvotes: 1

Views: 673

Answers (2)

Algonomaly
Algonomaly

Reputation: 99

I'm assuming that you are wanting to filter your list with the text box and order the result by the age property of each object? If you wish to do this, you'd just chain filters.

<tr ng-repeat="friend in friends | orderBy:'age' | filter : criteria">
  <td>{{friend.name}}</td>
  <td>{{friend.phone}}</td>
  <td>{{friend.age}}</td>
</tr>

Here is a plunker with an example of using multiple filters http://plnkr.co/edit/8rfitXitGhjjthUXujOL?p=info

Upvotes: 0

Dylan Watt
Dylan Watt

Reputation: 3387

{{}} is only for interpolation in non angular expressions. Since ng-repeat is executed against the scope, you can just reference the variable directly.

orderBy:criteria

Upvotes: 3

Related Questions