angularjs smart-table以编程方式排序

时间:2016-02-09 04:03:45

标签: javascript angularjs smart-table

我使用AngularJS的智能表插件设置了一个表。一切看起来都很好用。我不想让用户点击表头来触发排序,而是想以编程方式从我的Angular控制器中触发排序。我在这里的文档中没有看到这样做的方法:

http://lorenzofox3.github.io/smart-table-website/

我忽略了什么吗?

3 个答案:

答案 0 :(得分:2)

在JSFiddle上找到这个,可以帮助你:http://jsfiddle.net/vojtajina/js64b/14/

<script type="text/javascript" ng:autobind
src="http://code.angularjs.org/0.10.5/angular-0.10.5.js"></script>

<table ng:controller="SortableTableCtrl">
    <thead>
        <tr>
            <th ng:repeat="(i,th) in head" ng:class="selectedCls(i)" ng:click="changeSorting(i)">{{th}}</th>
        </tr>
    </thead>
    <tbody>
        <tr ng:repeat="row in body.$orderBy(sort.column, sort.descending)">
            <td>{{row.a}}</td>
            <td>{{row.b}}</td>
            <td>{{row.c}}</td> 
        </tr>
    </tbody>
</table>

答案 1 :(得分:1)

我发现如何做到这一点的快速入侵是通过设置表头st-sort属性然后触发该元素上的click()

<tr>
  <th id="myelement" st-sort="date" st-sort-default="reverse">Date</th> 
  ...
</tr>

然后:

 setTimeout(function() {
      document.getElementById('myelement').click()        
    }, 
  0);

答案 2 :(得分:0)

这是执行此操作的“角度”方法。编写指令。该指令将有权访问智能表控制器。它将能够调用控制器的按功能排序。我们将新指令命名为stSortBy。

下面的HTML包含标准的智能表语法糖。这里唯一的新属性指令是st-sort-by。那就是魔术发生的地方。它绑定到范围变量sortByColumn。这是要排序的列的字符串值

<table st-sort-by="{{sortByColumn"}}" st-table="displayedCollection" st-safe-src="rowCollection">
<thead>
<tr>
<th st-sort="column1">Person</th>
<th st-sort="column2">Person</th>
</tr>
</thead>
</table>

<button ng-click="toggleSort()">Toggle sort columns!</button>

这是连接到st表控制器的stSortBy指令

app.directive('stSortBy', function() {
    return {
        require: 'stTable',
        link: function (scope, element, attr, ctrl) {
            attr.$observe('stSortBy', function (newValue) {
                if(newValue) {
                    // ctrl is the smart table controller
                    // the second parameter is for the sort order
                    ctrl.sortBy(newValue, true);
                }
            });
        }
    };
});

这里是控制器。控制器在其范围内设置排序依据

app.controller("MyTableWrapperCtrl", ["$scope", function($scope) {
  $scope.sortByColumn = 'column2';
  
  $scope.toggleSort = function() {
     $scope.sortByColumn = $scope.sortByColumn === 'column2' ? 'column1' : 'column2';
     // The time out is here to guarantee the attribute selector in the directive
     // fires. This is useful is you do a programmatic sort and then the user sorts
     // and you want to programmatically sort back to the same column. This forces a sort, even if you are sorting the same column twice.
     $timeout(function(){
      $scope.sortByColumn = undefined;
     }, 0);
  };
}]);