在custom指令中成功使用$ filter(orderBy)后,HTML不会更新

时间:2014-01-18 11:43:26

标签: javascript jquery angularjs angularjs-directive angularjs-scope

我正在创建一个名为ngSortable的自定义指令,可以在单击该元素时对数组使用orderBy过滤器。我已经介入并确认数组正在正确排序,但视图没有更新。过滤器包含在范围内。$ apply(),所以我不确定它为什么不更新。我还在数组上放了一个范围。$ watch,看看是否正在播出更改,而$ watch没有捕获任何内容。我正在使用jquery click事件监听器,如果这有任何区别。如果有人能帮助我弄清楚我在做错了什么,我会非常感激。

HTML

<table class="table table-bordered table-condensed">
<thead>
    <tr>
        <th ng-sortable="policyAcordTypes" enable-multiple="true" data-field="description" style="width: 40%;">Acord Type</th>
        .....
    </tr>
</thead>
<tbody>
    <tr ng-repeat="item in policyAcordTypes" >
        <td style="width: 40%; min-width: 140px">
            <div>{{item.description}}</div>
        </td>
        ....
    </tr>
</tbody>

的Javascript

scope.$apply(function () {
    $filter('orderBy')(scope.$eval(attr.ngSortable), 'description');  
});

我试过这个...... 的的Javascript

scope.$apply(function () {
    var list = scope.$eval(attr.ngSortable);
    list = $filter('orderBy')(scope.$eval(attr.ngSortable), 'description');  
});

1 个答案:

答案 0 :(得分:1)

$filter('orderBy') 不会修改传入的数组,它会返回一个新的有序数组。您需要将返回的数组分配回作用域的属性。

不应使用scope.$eval(attr.ngSortable),而应使用[]运算符(标准javascript)

尝试:

scope.$apply(function () {
    scope[attr.ngSortable] = $filter('orderBy')(scope[attr.ngSortable], 'description');  
});

DEMO(点击标题会对行进行排序)