isaac weathers isaac weathers - 2 years ago 113
AngularJS Question

Set initial state of ng-show for orderBy in Angular

Trying to set the initial state of an arrow that I am showing for a list that is sortable. There are three columns and each one has a link bound to an

that when clicked will sort the list.

It's working as I need it to but the state of the up and down arrows do not show until clicked. And when I click one the other disappears. What I would like is for all the arrows to always show even before the user clicks and for each one to change direction on click of any of the three.

The basic link is this:

<a href="javascript:void(0)" ng-click="orderByField='dateAdded'; reverseSort = !reverseSort" class="ghostButtonSort dateLabel flrt">Date Received
<span ng-show="orderByField == 'dateAdded'">
<span ng-show="!reverseSort">^</span>
<span ng-show="reverseSort">v</span>

And right now I just have a basic setup in the scope:

$scope.orderByField = 'conditionId';

Answer Source

Initialize the values with defaults in your controller:

$scope.orderByField = 'dateAdded';
$scope.reverseSort = false;

Here's a simple Fiddle that demonstrates working sorting behavior:

In this demo you can change the sort column by clicking on column headings, and change the sort direction by clicking on the caret that appears next to the active sort column. This is achieved with:


<table id='peopleTable'>
          <a href="#" ng-click="sortOn = 'firstName'">First Name</a> 
          <i class="fa"
             ng-click="sortReverse = !sortReverse"
             ng-show="sortOn == 'firstName'"
             ng-class="sortReverse ? 'fa-caret-down' : 'fa-caret-up'">
      <!-- snip -->
      <tr ng-repeat='person in people | orderBy:sortOn:sortReverse'>


function MyCtrl($scope) {
    $scope.sortOn = 'lastName';
    $scope.sortReverse = false;

    $scope.people = [
            firstName: 'Joe',
            lastName: 'Smith',
            favoriteColor: 'Orange'
        }, {
            firstName: 'Jane',
            lastName: 'Doe',
            favoriteColor: 'Gray'
        }, {
            firstName: 'Zoey',
            lastName: 'Tester',
            favoriteColor: 'Blue'

I'm using FontAwesome for the carets, but you can use text, or images. sortReverse and sortOn are both initialized in the controller, so they have default values and will always be reflected in the UI.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download