Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS | orderBy filter not updated dynamically

I'm having trouble with the orderBy filter in AngularJS. Here's my setup:

<li ng-repeat="item in listItems.data | orderBy:order">
    <a ng-click="getRelated(item._id)">{{ item.title }}</a>
</li>

Part of the controller:

$scope.order = 'year';

$scope.listItems = $http.post($scope.url, {'filterType': 'abc', 'letter': $scope.params.letter});

$scope.setOrder = function(order) {
    $scope.order = order;
}

And finally the "switches" I would like to use for ordering the data

    <span class="sort--title">Sort by</span>
    <a ng-class="{true:'selected', false:''}[order=='title']" href="" ng-click="setOrder('title')" class="sort--attribute">Title</a>
    <a ng-class="{true:'selected', false:''}[order=='year']" href="" ng-click="setOrder('year')" class="sort--attribute">Year</a>
    <a ng-class="{true:'selected', false:''}[order=='length']" href="" ng-click="setOrder('length')" class="sort--attribute">Length</a>
    <a ng-class="{true:'selected', false:''}[order=='date_added']" href="" ng-click="setOrder('date_added')" class="sort--attribute">Date Added</a>

When I click the buttons, the list is not being re-ordered. When I manually change the initial $scope.order value, the list is ordered by the property. Also ng-class is updated correctly. I'm obviously missing out something!

like image 798
Teo.sk Avatar asked Dec 23 '12 15:12

Teo.sk


1 Answers

I don't think your idea is wrong. It does work. Here is the working plunker.

You must have something wrong somewhere else.

app.js

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

app.controller('MainCtrl', ['$scope', function ($scope) {
    'use strict';
    $scope.friends = [
        {name: 'John', phone: '555-1276'},
        {name: 'Mary', phone: '800-BIG-MARY'},
        {name: 'Mike', phone: '555-4321'},
        {name: 'Adam', phone: '555-5678'},
        {name: 'Julie', phone: '555-8765'}
    ];
    $scope.setOrder = function (order) {
        $scope.order = order;
    };
}]);

main html

<ul class="nav nav-pills">
    <li ng-class="{'active': order=='name'}"><a href="#" ng-click="setOrder('name')">name</a></li>
    <li  ng-class="{'active': order=='phone'}"><a href="#" ng-click="setOrder('phone')">phone</a></li>
</ul>
<ul>
    <li data-ng-repeat="friend in friends|orderBy:order">
        <span class="name">{{friend.name}}</span>
        <span class="phone">{{friend.phone}}</span>
    </li>
</ul>
like image 181
maxisam Avatar answered Oct 12 '22 11:10

maxisam