javascript - Using a Custom Filter in AngularJs -
i relatively new angularjs , came across problem when using orderby: in regards sorting objects, borrowed custom filter sort objects not understanding correct syntax use filter appropriately wont sort key in object want to:
js:
<tbody ng-repeat="(field, profile) in currentsample.dsprofile | orderbyobject:'profile[display-name]' track $index"> <tr ng-style="$index % 2 === 0 && {'background-color': '#ffffff'} || $index % 2 === 1 && {'background-color': '#f9f9f9'}"> <td style="width: 19%; margin: 2px; padding: 0px;" ng-style="profile['shown-in-details'] == true && {'background-color': 'gold'} || profile['shown-in-details'] == false && {'background-color': 'transparent'}"> <span class="btn-property" ng-click="showingenericdetails(currentsample, field)" uib-tooltip="{{field}}" tooltip-placement="right"> <b>{{profile["display-name"]}}</b> </span>
filter:
app.filter('orderbyobject', function() { return function(items, field, reverse) { var filtered = []; angular.foreach(items, function(item) { filtered.push(item); }); filtered.sort(function (a, b) { return (a[field] > b[field] ? 1 : -1); }); if(reverse) filtered.reverse(); return filtered; }; });
without filter
<table id="data-sources-table" class="table drag-drop"> <tbody ng-repeat="(field, profile) in currentschema.sprofile | orderby:property track $index"> <tr ng-style="$index %2 === 0 && {'background-color': '#ffffff'} || $index %2 === 1 && {'background-color': '#f9f9f9'}"> <td style="width: 180px"> <span class="btn-property"> <b>{{field}}</b>
since can't use orderby directly because filter
needs filter collection, should parse items collection, this:
var app = angular.module('app', []); app.controller('mainctrl', function($scope) { var testobj = { "obj1":{ "id":1, "title":"title1" }, "obj2":{ "id":2, "title":"title2" }, "obj3":{ "id":3, "title":"title3" } }; $scope.testarray = []; object.keys(testobj).foreach(function(key) { $scope.testarray.push(testobj[key]); }); // can use $scope.testarray normal array in view. });
<!doctype html> <html ng-app="app"> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script> </head> <body ng-controller="mainctrl"> <ul> <li ng-repeat="obj in testarray | orderby: title: reverse" ng-bind="obj.title"></li> </ul> <button type="button" ng-model="reverse" ng-click="reverse = !reverse">reverse order</button> </body> </html>
note: doing way, need parse objects array once, instead of doing everytime when needs sort.
reference: https://docs.angularjs.org/error/orderby/notarray
i hope helps!
edit:
i noticed you're using construction:
ng-style="$index % 2 === 0 && {'background-color': '#ffffff'} || $index % 2 === 1 && {'background-color': '#f9f9f9'}"
you can simplify life using native special-properties, can have this:
ng-style="$even && {'background-color': '#ffffff'} || $odd && {'background-color': '#f9f9f9'}"
note: change ng-repeat <tr>
tag.
Comments
Post a Comment