angularjs - Angular sort by a calculated value -
i have app display list of elements, every 1 different properties, , 1 of properties used value factory, , want able sort list calculated value.
i know can save calculated value in list , sort, way?
this fiddle , code
angular .module("app", []) .controller('controller', controller) .factory('factory', factory) .directive('val', val) .controller('valcontroller', valcontroller) directivecontroller.$inject = [ 'factory']; function controller() { var vm = this; vm.results = [{ "id": "1", "pos": 1 }, { "id": "2", "pos": 2 }, { "id": "3", "pos": 3 }, { "id": "4", "pos": 4 }]; console.info(json.stringify(vm.results)); } function val() { return { replace: true, scope: {}, bindtocontroller: { id: '@' }, controller: valcontroller, controlleras: 'vm', template: '<td ng-bind="vm.value"></td>' }; } function valcontroller(factory) { var vm = this; vm.value = factory.getvalue(vm.id); } function factory() { var values = { '1': 'green', '2': 'blue', '3': 'yellow', '4': 'red' }; return { getvalue: function(id) { return values[id]; } } }
and simple html
<div> <table> <thead> <tr> <th>id</th> <th>pos</th> <th>value</th> </tr> </thead> <tbody> <tr ng-repeat="result in vm.results | orderby:'+value'"> <td ng-bind="result.id"></td> <td ng-bind="result.pos"></td> <td val id="{{result.id}}"></td> </tr> </tbody> </table> </div>
many thanks!
for since property value isn't reflective of sort there numerous ways this. short of modifying items property require sorting in 1 place or another
a custom filter convenient since can inject factory it. since filter used on array, return sorted array based on value mapping factory item
.filter('valuesort',function(factory){ return function(items){ if(!items) return; return items.sort(function(a, b){ return factory.values[a.pos] > factory.values[b.pos]; }); } });
view
<tr ng-repeat="result in vm.results | valuesort">
note: tweaked factory return values
object reference demo
Comments
Post a Comment