ChanChow ChanChow - 1 month ago 8
AngularJS Question

How to sort on input text in angular

I am new to angular. I have an input text box where I am going to enter sorting criteria like "rating" and "date". I have a controller defined with data.

comments: [
{
rating:5,
date:"2012-10-16T17:57:28.556094Z"
},
{
rating:4,
date:"2014-09-05T17:57:28.556094Z"
}]


Can someone help me how to define filters which will do the sorting based on input.
Thanks

Answer

Working Plnkr

In this example, when you type rating or date in input text field, it will sort the data based on this value. I have called the method on key press. If you want to sort after clicking on sort button, add a button and call he sorting method on ng-click.

var myApp = angular.module('myApp',[]);

myApp.controller('MyController',function($scope,$filter){
  $scope.test = 'This is a test!';

  $scope.comments = [
                           {
                               rating:5,
                               date:"2012-10-16T17:57:28.556094Z"
                           },
                           {
                               rating:4,
                               date:"2014-09-05T17:57:28.556094Z"
                           },
                           {
                               rating:7,
                               date:"2010-09-05T17:57:28.556094Z"
                           }]; 
  $scope.comments2 = $scope.comments;
  $scope.$watch('sortItem', function(val)
    { 

      if(val==='rating' || val==='date'){
         $scope.comments = $filter('orderBy')($scope.comments2,val);
      }
      else{
        return;
      }

    });                         

}); 

Hope that solve your problem.

Comments