Javascript / AngularJS - Convert string to number in orderBy

问题: I have a simple problem. When I try to order the ID, it's ordering like 1,12,13,2,20 So I think it assumes this as a string. I tried to use number but with no...

问题:

I have a simple problem. When I try to order the ID, it's ordering like

1,12,13,2,20

So I think it assumes this as a string.

I tried to use number but with no help.

What can I do?

thead

<th class="text-center">
    Ticket ID&nbsp;
    <a uib-tooltip="Sort by" ng-click="vm.sortBy('TICKET_ID');">
        <i class="glyphicon glyphicon-sort pull-right"></i>
    </a>
</th>

body

 <tr class="text-center" ng-repeat="ticket in filteredTickets = (vm.tickets | 
     orderBy : vm.propertyName : vm.reverse | 
     filter : vm.search | 
     limitTo : vm.itemsPerPage : vm.itemsPerPage * (vm.currentPage-1))">                  
     <td>{{ticket.TICKET_ID | number}</td>
     <!-- 'number' doesn't help... -->

controller

// table ordering
vm.propertyName = 'TICKET_ID';
vm.reverse = false;

vm.sortBy = function(propertyName) {
    vm.reverse = !vm.reverse;
    vm.propertyName = propertyName;
};

回答1:

Just convert string values to int and let orderBy filter of angularjs do the job for you

$scope.getNumber = function(row){
    return parseInt(row.TICKET_ID);
};

<tr class="text-center" ng-repeat="ticket in tickets | orderBy:getNumber:true"> 

also orderBy takes a second parameter (true / false) for asc / desc ordering


回答2:

You shouldn't use orderBy, nor filter in an angularJs app. In angular, both the pipes where removed, because (official docs):

Angular doesn't provide pipes for filtering or sorting lists. Developers familiar with AngularJS know these as filter and orderBy. There are no equivalents in Angular.

This isn't an oversight. Angular doesn't offer such pipes because they perform poorly and prevent aggressive minification. Both filter and orderBy require parameters that reference object properties. Earlier in this page, you learned that such pipes must be impure and that Angular calls impure pipes in almost every change-detection cycle.

Filtering and especially sorting are expensive operations. The user experience can degrade severely for even moderate-sized lists when Angular calls these pipe methods many times per second. filter and orderBy have often been abused in AngularJS apps, leading to complaints that Angular itself is slow. That charge is fair in the indirect sense that AngularJS prepared this performance trap by offering filter and orderBy in the first place.


Instead, implement a simple order and filtering logic in your controller and pass the data sorted and filtered to ng-repeat; now you can define exactly when and how ordering, filtering, ... should be done.

In your controller, converting is as easy as

Number(anyString);

...

  • 发表于 2018-07-05 20:17
  • 阅读 ( 576 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除