Reputation: 2143
I have a project where I want to display multiple counts on different filtered results of the same array. I do this with a binding which is inside an ng-repeat like so:
{{ (queue | filter: {doctorName:d.doctorName} | filter: {status:'Scheduled'}).length }}
Is there a way I can re-use that result, I would like to use the result in an ng-class but I can only do this by running the same query like so:
ng-class="(queue | filter: {doctorName:d.doctorName} | filter: {status:'Scheduled'}).length ? 'showHint' : 'hideHint'"
Is there an easier more efficient way to do this?
Upvotes: 0
Views: 103
Reputation: 43
The easier way would be to do like @origonof suggests.
However if you want to only do the calculation once for each doctor you could use the Controller as syntax.
I have modified your example http://jsfiddle.net/krausekjaer/4yfwckzv/7/
Here is the controller I added:
docApp.controller('DocterController', function ($scope, $filter) {
var self = this;
self.docQueue = $filter('filter')($scope.queue, {doctorName: $scope.d.doctorName});
});
and it can be used in the html like this
<div ng-controller="DocterController as docCtrl">
<div>{{ d.doctorName }}</div>
<div ng-class="(docCtrl.docQueue | filter: {status:'Scheduled'}).length ? 'showHint' : 'hideHint'">
Bookings: {{ (docCtrl.docQueue | filter: {status:'Scheduled'}).length }}
</div>
<div ng-class="(docCtrl.docQueue | filter: {status:'Waiting'}).length ? 'showHint' : 'hideHint'">
Queue: {{ (docCtrl.docQueue | filter: {status:'Waiting'}).length }}
</div>
<div ng-class="(docCtrl.docQueue | filter: {status:'Served'}).length ? 'showHint' : 'hideHint'">
Active: {{ (docCtrl.docQueue | filter: {status:'Served'}).length }}
</div>
</div>
Note I updated angular to a never version as well, the Controller as functionality should be present in 2.0 also if I remeber correctly.
Upvotes: 1
Reputation: 795
Move the filter from the view to the controller:
myApp.controller('myControllerNameCtrl', function($scope, $filter) {
$scope.queue = ...;
var firstFilter = $filter('firstFilter')(queue, {doctorName: d.doctorName});
var secondFilter = ...;
$scope.filteredQueue = secondFilter;
});
Upvotes: 0