简体   繁体   English

我如何将一个键绑定到angular js中的排序类型?

[英]How can i bind a key to a sort type in angular js?

there is a get request which conatins key:value data now i have a table header which contains key and value i want it to sort the value as it could be done before: 现在有一个包含key:value数据的get请求,现在我有一个表头,其中包含键和值,我希望它对值进行排序,就像以前可以做到的那样:

 <th>
    <a href="#" ng-click="sortType = 'scenarioNo'; sortReverse = !sortReverse">
    scenarioNo
    <span ng-show="sortType == 'scenarioNo' && !sortReverse" class="fa fa-caret-down"></span>
    <span ng-show="sortType == 'scenarioNo' && sortReverse" class="fa fa-caret-up"></span>
    </a>
</th>

now i want to do it dynamically as such the key will be a table head and the values could then be sorted on click of the header: 现在我想动态地执行此操作,因为键将是表头,然后可以在单击标题时对值进行排序:

    <tr ng-repeat="item in myEntity | limitTo:1">
    <th></th>
    <th ng-repeat="(key,value) in item">
        <a href="#" ng-click="sortType = '{{key}}'; sortReverse = !sortReverse">{{key}}<span ng-show="sortType == '{{key}}' && !sortReverse" class="fa fa-caret-down"></span>
  <span ng-show="sortType == '{{key}}' && sortReverse" class="fa fa-caret-up"></span>
  </a>
    </th>
</tr>

i have used the angular sortRevers to sort the values of the table. 我已经使用了角度sortRevers对表的值进行排序。 how can i make the headers clickable and sortable..? 我怎样才能使标题可点击和可排序..? does data binding work inside the sorttype like in the above code 像上面的代码中那样,数据绑定是否在sorttype中起作用

Do the sort in the controller instead of on the html page 在控制器中而不是在html页面上进行排序

<tr ng-repeat="item in myEntity | limitTo:1">
     <th></th>
     <th ng-repeat="(key,value) in item">
         <a href="#" ng-click="sort(key, !sortReverse)">{{key}}
         <span class="fa" 
               ng-if="sortType == key"
               ng-class="{'fa-caret-down' :  sortReverse, 'fa-caret-up' : !sortReverse}">
          </span>
     </a>
     </th>
</tr> 

and the controller 和控制器

sort(key, sortReverse){
  //Do the sortlogic
  $scope.sortType = sortReverse;
  $scope.key = key;
}

You must use global scope (in controller) sort parameters because ng-repeat has is own scope. 您必须使用全局范围(在控制器中)的排序参数,因为ng-repeat具有自己的范围。

Very similar example like @Bo Vandersteene add, but works and with Fiddle: 像@Bo Vandersteene这样非常相似的示例可以添加,但是可以和Fiddle一起使用:

  <tr ng-repeat="item in myEntity | limitTo:1">
       <th></th>
       <th ng-repeat="(key,value) in item">
           <a href="#" ng-click="sort(key, !sortReverse)">
            {{key}}
            <span class="fa" ng-class="{'fa-caret-down' :  sortReverse, 'fa-caret-up' : !sortReverse}" ng-show="sortKey == key"></span>
           </a>
       </th>
  </tr> 

In controller: 在控制器中:

$scope.sort = function(key, reverse) {
  $scope.sortKey = key;
  $scope.sortReverse = !$scope.sortReverse;
}

Fiddle: https://jsfiddle.net/23z8urzw/1/ 小提琴: https : //jsfiddle.net/23z8urzw/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM