指令中的AngularJS谓词不起作用

时间:2014-02-17 17:54:46

标签: html angularjs angularjs-directive directive

我在指令中排序有问题。我想使用具有“名称”和“文本”属性的对象动态创建表头。 'Name'包含逻辑名称和字段的'Text'显示名称。当我不在ng-repeat和动态列中使用谓词时,一切正常。

HTML:

<ng-my-table 
    ng-columns="[
            { Text: 'First name', Name: 'FirstName' },
            { Text: 'Last name', Name: 'LastName' }
        ]">
</ng-my-table>

指令模板:

<thead>
    <tr>
        <th ng-repeat="column in ngColumns" ng-click="predicate='{{column.Name}}'; reverse=!reverse">{{column.Text}}</th>
    </tr>
</thead>

编译的表头看起来像静态但不起作用。

有人能帮助我吗?感谢。

3 个答案:

答案 0 :(得分:2)

您需要将谓词与循环的范围对象相关联。

也就是说,你的标记应该是:

<th ng-repeat="column in ngColumns| orderBy:predicate:reverse"
    ng-click="predicate='{{column.Name}}'; reverse=!reverse">{{column.Text}}</th>

但是,建议 - 将ng-click指令内的代码移动到作用域的控制器函数 - 更容易维护。

所以,你的控制器中的功能是这样的:

//Don't forget to initialize
$scope.predicate = $scope.ngColumns[0].Name;
$scope.reverse = false;

$scope.sortColumn = function (columName) {
    $scope.predicate = columnName;
    $scope.reverse = !$scope.reverse
}

您的视图代码现在看起来像:

<th ng-repeat="column in ngColumns| orderBy:predicate:reverse"
        ng-click="sortColumn(column.Name)">{{column.Text}}</th>

答案 1 :(得分:1)

predicate='{{column.Name}}';看起来像是一个问题来源。

ng-click指令不使用角度表达式语法。尝试以这种方式写predicate=column.Name;

答案 2 :(得分:1)

以下是工作样本:

指令模板:

<thead>
    <tr>
        <th ng-repeat="column in ngColumns" ng-click="SortColumn(column.Name)">{{column.Text}}</th>
    </tr>
</thead>
<tbody>
    <tr ng-repeat="item in ngModel | orderBy:predicate:reverse">
    ...
    ...

指令控制人:

controller: ["$scope", "$http", function ($scope, $http) {
            // convert string to object
            $scope.ngColumns = $scope.$eval($scope.ngColumns);
            // models for sorting
            $scope.predicate = $scope.ngColumns[0].Name;
            $scope.reverse = false;
            // sort function
            $scope.SortColumn = function (columnName) {
                $scope.predicate = columnName;
                $scope.reverse = !$scope.reverse
            }
        }]

我希望它有所帮助。