【问题标题】:AngularJS - select the first option in list that's reordered in the templateAngularJS - 选择模板中重新排序的列表中的第一个选项
【发布时间】:2013-06-22 03:19:48
【问题描述】:

我昨天才开始使用 Angular JS,如果我问的是明显的问题,抱歉。我要做的是使我的第一个选项成为默认选择的选项,但由于它是在前端订购的,因此选择了错误的选项。我认为我应该在选择第一项之前重新排序从控制器内的 API 调用返回的数据?

这是我的选择:

<select ng-model="clientsList" ng-options="c.Name for c in clients | orderBy:'Name'"></select>

这是我的控制器:

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];
    });
}

【问题讨论】:

    标签: javascript angularjs filtering


    【解决方案1】:

    只需使用相同的过滤器对控制器中的数据进行排序:

    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>
    

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

    [filterName]Filter
    

    【讨论】:

    • 差不多 3 年后,这仍然像一个魅力。谢谢! :)
    猜你喜欢
    • 1970-01-01
    • 2012-03-21
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多