动态角度表不排序

时间:2015-09-17 22:09:10

标签: javascript angularjs

我在排序动态Angular表时遇到了一些困难。

如果我对表头进行硬编码,它就可以了。 小提琴:https://jsfiddle.net/xgL15jnf/

<thead>
    <tr>
        <td>
            <a href="#" ng-click="sortType =  'id';    sortReverse = !sortReverse">id
                <span   ng-show="sortType  == 'id' && !sortReverse" class="glyphicon glyphicon-arrow-down"></span>
                <span   ng-show="sortType  == 'id' &&  sortReverse" class="glyphicon glyphicon-arrow-up"></span>
            </a>
        </td>
        <td>
            <a href="#" ng-click="sortType =  'name';    sortReverse = !sortReverse">name
                <span   ng-show="sortType  == 'name' && !sortReverse" class="glyphicon glyphicon-arrow-down"></span>
                <span   ng-show="sortType  == 'name' &&  sortReverse" class="glyphicon glyphicon-arrow-up"></span>
            </a>
        </td>
        <td>
            <a href="#" ng-click="sortType =  'cost';    sortReverse = !sortReverse">cost
                <span   ng-show="sortType  == 'cost' && !sortReverse" class="glyphicon glyphicon-arrow-down"></span>
                <span   ng-show="sortType  == 'cost' &&  sortReverse" class="glyphicon glyphicon-arrow-up"></span>
            </a>
        </td>
    </tr>
</thead>

但是,如果我动态构建标头,它不会。 小提琴:https://jsfiddle.net/m31d00sz/

<thead>
    <tr>
        <td ng-repeat="column in cols">
            <a href="#" ng-click="sortType = '{{column}}';    sortReverse = !sortReverse">{{column}}
                <span ng-show="sortType   == '{{column}}' && !sortReverse" class="glyphicon glyphicon-arrow-down"></span>
                <span ng-show="sortType   == '{{column}}' &&  sortReverse" class="glyphicon glyphicon-arrow-up"></span>
            </a>
        </td>
    </tr>
</thead>

搜索/过滤器适用于两个小提琴。

我希望我能够忽略一些简单的事情,如果有人可以看一眼并提供一些指导,我将不胜感激!

1 个答案:

答案 0 :(得分:1)

您不需要在{{column}}指令中使用插值大括号ngClick。它应该是:

ng-click="sortType = column; sortReverse = !sortReverse"

还有一个问题。由于ngRepeat指令在您单击时每次迭代都会创建新的子范围,因此实际上会修改本地范围sortReversesortType属性。简单的解决方法是利用原型继承,在这种情况下,ngClick将使用由原型链解析的上部范围的属性。

对于控制器定义中的这个

$scope.sort = {
    type: 'id',
    reverse: false
};

并在模板中:

<td ng-repeat="column in cols"> 
    <a href="#" ng-click="sort.type = column; sort.reverse = !sort.reverse">
        {{column}}
        <span ng-show="sort.type == column && !sort.reverse" class="glyphicon glyphicon-arrow-down"></span>
        <span ng-show="sort.type == column && sort.reverse" class="glyphicon glyphicon-arrow-up"></span>
    </a>

</td>

<tr ng-repeat="row in rows | orderBy:sort.type:sort.reverse | filter:searchData">
    <td ng-repeat="column in cols">{{row[column]}}</td>
</tr>

演示: https://jsfiddle.net/m31d00sz/1/