This issue has been frustrating me for a while.
When loading the page, default sorting for a table is set via this code:
$scope.sort = {
field: 'date',
dir: 'asc'
};
Sorting is changed via user clicking on table headings, like so:
<th ng-class="{'sort-desc': sorted('date', 'desc'), 'sort-asc': sorted('date', 'asc')}" class="sortable">
<a href="#" ng-click="setSort('date')">Date</a>
</th>
Here's the setSort code:
$scope.setSort = function(field) {
if ($scope.sort.field == field)
$scope.sort.dir = ($scope.sort.dir == 'desc') ? 'asc' : 'desc';
else
$scope.sort.field = field;
$scope.update();
};
and sorted
$scope.sorted = function(field, dir) {
return ($scope.sort.field == field && $scope.sort.dir == dir);
};
On initial pageload, the default sort (date-asc) is applied to the data within the table however the sort-asc is not applied. When changing the sort column, it will display fine - it's just the initial page load.
How can I get angular to evaluate correctly on pageload?
After some more poking around I figured out the issue: I had $scope.sort
defined twice, once as an object and once as a function.
For some reason, it was working once $scope.sort.dir
and $scope.sort.field
were re-defined by changing the sorting but the original values were overwritten by my function definition.
Lesson learnt - be more careful with variables names.