Viveka
Viveka

Reputation: 237

Perform orderBy when dropdown is selected angularjs

I have a drop down list consisting of name and address. if name is selected then my list should be sorted with name. My code is not working properly` Order By

<div class="col-xs-2">
        <select class="form-control" ng-change="changedvalue()" ng-model="Tosort.order">
            <option value="None">-- Select --</option>
            <option ng-model="Tosort.order" value="Name">Name</option>
            <option ng-model="Tosort.order" value="Address">Address</option>
        </select>
    </div>
<li ng-repeat="x in details | filter: Tofilter.country | orderBy:sort.value">

Upvotes: 4

Views: 14339

Answers (2)

Mikko Viitala
Mikko Viitala

Reputation: 8404

I see you got lot's of answers while I was still writing my example. Damn you're fast! :)

Anyway, this would be content of your HTML

<body ng-controller="MyCtrl">
  <div>
    <!-- text input for filtering -->
    <label>Country filter</label>
    <input type="text" ng-model="countryFilter"></input>

    <!-- options to order (filtered) results -->
    <label>Order by</label>
    <select ng-model="selectedOrder" ng-options="option for option in options"></select>
  </div>

  <ul>
    <!-- show results: filter by country name and order by selected property name -->
    <li ng-repeat="detail in details | filter:{country: countryFilter} | orderBy:selectedOrder">{{ detail }}</li>    
  </ul>
</body>

And this would be related controller

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

app.controller('MyCtrl', function($scope) {      
  // order by options
  $scope.options = ['country', 'address'];

  // all countries
  $scope.details = [{
    id:1, country:'Country 1', address:'Address C'
  },{
    id:2, country:'Country 2', address:'Address B'
  },{
    id:3, country:'Country 3', address:'Address A'
  }];
});

For future reference, working plunker here http://plnkr.co/edit/02Y3b7

Upvotes: 2

Abhinav Gujjar
Abhinav Gujjar

Reputation: 2620

You need to simply use ng-model instead of the ng-change() event. There are some other issues in your code as well like you need to provide ng-model only on the select tag. I think you may need to revisit some angular basics. I've shown how it could work below. the select tag will be bound to "sortBy" and the same is used in the "orderBy" filter

<div class="col-xs-2">

        <select class="form-control" ng-model="sortBy">
            <option value="None">-- Select --</option>

            <option value="Name">Name</option>
            <option value="Address">Address</option>

        </select>
    </div>



<li ng-repeat="x in details | filter: Tofilter.country | orderBy:sortBy">

Upvotes: 3

Related Questions