orderBy不使用具有服务返回值的列

时间:2015-06-25 07:42:42

标签: angularjs angularjs-service angularjs-filter

我在数据中显示一些基本的个人信息,并使用orderBy对行进行排序。除了列之外,一切正常,该值实际上是从服务中检索的。在这种情况下,当我通过按第一列中的标题来求助行时,所有列都会使用该列。

我有一个fiddle来测试它,这就是代码。

<div ng-controller="MyController as vm">
    <table>
        <thead>
            <tr>
                <th><a href="" ng-click="vm.order('no')">No</a></th>
                <th>Name</th>
                <th>Age</th>            
                <th>Id</th>
                <th>NameById</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="person in vm.results | orderBy:vm.predicate:vm.reverse track by $index">
                <td ng-bind="person.no"></td>
                <td ng-bind="person.name"></td>
                <td ng-bind="person.age"></td>
                <td ng-bind="person.id"></td>
                <td name-by-id pid="{{person.id}}"></td>
            </tr>           
        </tbody>
    </table>
</div>

(function() {

    angular

    .module("app",[])

    .controller('MyController', MyController)    
    .service('namesService', namesService)    
    .controller('NameByIdController', NameByIdController)
    .directive('nameById', nameById);

    NameByIdController.$inject = ['namesService'];    

    function namesService() {        
        names = {
            '1': 'John',
            '2': 'Mary',
            '3': 'Mike',
            '4': 'Adam',
            '5': 'Julie'
        };

         this.getName = getName;

        function getName(id) {
            return names[id];
        }
    }

    function MyController() {        
        var vm = this;    

        vm.predicate = 'no';
        vm.reverse = false;
        vm.order = order;

        vm.results = [
            { no: 1,    name: 'John',    age: 10,    id: '1' },
            { no: 2,    name: 'Mary',    age: 19,    id: '2' },
            { no: 3,    name: 'Mike',    age: 21,    id: '3' },
            { no: 4,    name: 'Adam',    age: 35,    id: '4' },
            { no: 5,    name: 'Julie',   age: 29,    id: '5' }
        ];

        function order(predicate) {
            vm.reverse = (vm.predicate === predicate) ? !vm.reverse : false;
            vm.predicate = predicate;
        }   
    }

    function nameById() {
        return {
            scope: {
                pid: '@'
            },
            controller: NameByIdController,
            controllerAs: 'vm',
            bindToController: true,
            template: '<div ng-bind="vm.serviceName"></div>'
        }
    }

    function NameByIdController(namesService) {        
        var vm = this;
        vm.serviceName = namesService.getName(vm.pid);
    }

})();

有谁知道为什么会发生这种情况以及如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您正在$index明确跟踪。将您的ng-repeat指令更改为

"person in vm.results | orderBy:vm.predicate:vm.reverse"