Looking at a list with filters attached, I am trying to count the items and show a message if there are no items...
<li ng-repeat="item in items = (items | sortWithTab:tab | filter:search")>
{{ item.name }}
</li>
<div ng-if="items.length === 0">No items</div>
The 'items' set includes a tab
field with a name, along with buttons to filter based on that name which updates the $scope.tab
.
To display the number of items in the list, I use items.length
, which works fine. However, when I go back to a tab I previously clicked on, it doesn't update. Can anyone explain why?
See the example below:
var app = angular.module('App', []);
app.controller('SampleCtrl', ['$scope',
function($scope) {
$scope.tab = 'all';
$scope.changeTab = function(tab)
{
$scope.tab = tab;
}
$scope.items = [
{name: 'One', tab: 'live'},
{name: 'Two', tab: 'today'},
{name: 'Three', tab: 'today'},
{name: 'Four', tab: 'today'},
{name: 'Five', tab: 'live'},
{name: 'Six', tab: 'today'},
{name: 'Seven', tab: 'today'},
{name: 'Eight', tab: 'live'}
];
}]);
app.filter('sortWithTab', function() {
return function(list, tab) {
var filtered;
var i;
if (tab == 'all') {
return list;
} else if (tab == 'today') {
filtered = [];
for (i = 0; i < list.length; i++) {
if(list[i].tab == 'today')
filtered.push(list[i]);
}
return filtered;
} else if (tab == 'live') {
filtered = [];
for (i = 0; i < list.length; i++) {
if(list[i].tab == 'live')
filtered.push(list[i]);
}
return filtered;
} else {
return list;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App" ng-controller="SampleCtrl">
<a ng-click="changeTab('all')">All</a>
<a ng-click="changeTab('today')">Today</a>
<a ng-click="changeTab('live')">Live</a>
<ul>
<li ng-repeat="item in items = (items | sortWithTab:tab)">
{{ item.name }}
</li>
Total: {{ items.length }}
</ul>
</div>