表头的AngularJS指令

Bri*_*ian 17 angularjs angularjs-directive

我正在尝试编写一个指令来处理更改表头的图标类.我想要的是(我相信无论如何)处理表头排序的标准方法.该指令将添加一个链接元素,并在用户单击按desc排序时将图标更改为desc,再次单击按asc并再次按该图标排序.这是我到目前为止所做的,但我现在不知道如何处理图标类以及重置同一个表但在指令范围之外的其他元素.任何帮助都会很棒!

angular.directive("tableHeaders", function() {
return {
    restrict: 'E',
    scope: {},
    template:'<i class="glyphicon glyphicon-filter"></i>',
    link: function(scope, element, attrs) {
        attrs.class = 'glyphicon glyphicon-sort-by-alphabet-alt';
    }
}
});
Run Code Online (Sandbox Code Playgroud)

这是我对html方面的看法:

<th>First Name<a ng-click="newOrderBy('_firstName')"><table-headers></table-headers></a></th>
<th>Last Name<a ng-click="newOrderBy('_lastName')"><table-headers></table-headers></a></th>
<tr ng-repeat="item in items | orderBy:orderBy:reverse>
<td>{{item._firstName}}</td>
<td>{{item._lastName}}</td>
</tr>
Run Code Online (Sandbox Code Playgroud)

订单目前在控制器中处理:

   $scope.newOrderBy = function(order) {
        $scope.orderBy = order;
        $scope.reverse = !$scope.reverse;
    };
Run Code Online (Sandbox Code Playgroud)

Nic*_*RIC 43

您需要做的是使用您的指令为每个元素提供订单和当前订单(来自您的控制器的订单).

BTW我认为你的指令将更好地匹配作为属性而不是标签.您可以检查以下代码:

angular.module('myApp', []).directive("sort", function() {
return {
    restrict: 'A',
    transclude: true,
    template : 
      '<a ng-click="onClick()">'+
        '<span ng-transclude></span>'+ 
        '<i class="glyphicon" ng-class="{\'glyphicon-sort-by-alphabet\' : order === by && !reverse,  \'glyphicon-sort-by-alphabet-alt\' : order===by && reverse}"></i>'+
      '</a>',
    scope: {
      order: '=',
      by: '=',
      reverse : '='
    },
    link: function(scope, element, attrs) {
      scope.onClick = function () {
        if( scope.order === scope.by ) {
           scope.reverse = !scope.reverse 
        } else {
          scope.by = scope.order ;
          scope.reverse = false; 
        }
      }
    }
}
});
Run Code Online (Sandbox Code Playgroud)

和它一起使用的plunker:http://plnkr.co/edit/P4cAm2AUGG36nejSjOpY?p=preview

该指令用作:

<thead>
  <tr>
    <th sort by="order" reverse="reverse" order="'name'">Name</th>
    <th>Phone</th>
    <th sort by="order" reverse="reverse" order="'age'">Age</th>        
  </tr>
</thead>
Run Code Online (Sandbox Code Playgroud)

  • 这是一个有用的,聪明的方法,但它不提供完全封装:如果页面上有多个表,如果在`by`中保留相同的值,则最终会一次排序两个表的风险/或`reverse`属性. (5认同)