AngularJS - 如何获得ng-repeat orderby中的第一项:'title'

时间:2013-10-04 02:28:00

标签: angularjs

我想知道在更改ng-repeat中的顺序后如何获取第一项的数据。

我创建了加载第一项数据的jsfiddle。 我想在orderBy title之后得到第一个项目。

http://jsfiddle.net/xTJr3/1/

<div ng-controller="AppCtrl">
    <div data-items></div>
</div>

angular.module('App', []).
// sample data
controller('AppCtrl', function($scope){
    $scope.items =[
        {'title': 'Item 3'},
        {'title': 'Item 2'},
        {'title': 'Item 1'}
    ]
}).
directive('items', function(){
    return {
        template: '<span ng-repeat="item in items | orderBy:\'title\'">{{item.title}}</span>'+
        '<h1>{{currentItem}}</h1>',
        controller: function($scope){
            // wants to get first item's title after ordered by title.
            // it should be Item 1
            $scope.currentItem = $scope.items[0].title;
        }
    }
})

1 个答案:

答案 0 :(得分:3)

有不同的方法使这项工作。最简单的是直接在控制器中使用orderByFilter,这样控制器和放大器都可以。视图共享相同的items

Demo link

directive('items', function(){
    return {
        template: '<span ng-repeat="item in items">{{item.title}}</span>'+
        '<h1>{{currentItem}}</h1>',
        controller: function($scope, orderByFilter){  
            $scope.items = orderByFilter($scope.items, 'title');
            $scope.currentItem = $scope.items[0].title;
        }
    }
})
相关问题