AngularJS - 选择列表中第一个在模板中重新排序的选项

ten*_*i_a 3 javascript filtering angularjs

我昨天刚开始使用Angular JS,对不起,如果我问一些明显的东西.我要做的是在我的选择中选择默认选择的第一个选项,但由于它是在前端订购的,因此选择了错误的选项.我想在选择第一项之前,我应该重新排序从控制器内部的API调用中返回的数据?

这是我的选择:

<select ng-model="clientsList" ng-options="c.Name for c in clients | orderBy:'Name'"></select>
Run Code Online (Sandbox Code Playgroud)

这是我的控制器:

function MyCtrl($scope, $http) {
    $scope.init = $http.jsonp('http://MY-API?callback=JSON_CALLBACK')
    .then( function ( response ) {
        $scope.clients = response.data;
        // need to select something, unfortunately, this won't be the first option on the front end because it's re-ordered alphabetically there
        $scope.clientsList = $scope.clients[0];
    });
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*wie 5

只需使用相同的过滤器在控制器中订购数据:

function MyCtrl($scope, $http, orderByFilter) {
  $scope.init = $http.jsonp('http://MY-API?callback=JSON_CALLBACK')
  .then( function ( response ) {
    $scope.clients = orderByFilter(response.data, 'Name');
    $scope.clientsList = $scope.clients[0];
  });
}

<select ng-model="clientsList" ng-options="c.Name for c in clients"></select>
Run Code Online (Sandbox Code Playgroud)

注意:您可以使用以下符号在控制器内注入AngularJS过滤器:

[filterName]Filter
Run Code Online (Sandbox Code Playgroud)