如何同步 select 和 AngularJS 中的 GET-param?

How synchronize select and GET-param in AngularJS?

我在页面上有一些过滤器,我需要将 select 元素的值与 GET 参数同步。

<div ng-app="TourSearchApp">
    <form ng-controller="SearchFilterCtrl">
       <select ng-model="country" ng-options="item.id as item.name for item in countries">
            <option value="">Choose country</option>
        </select>
    </form>
</div>

<script>
    var app = angular.module('TourSearchApp', []);

    app.controller('SearchFilterCtrl', ['$scope', '$http', '$location', function($scope, $http, $location) {        
        $http.get('/api/countries/').success(function(data) {
            $scope.countries = data;
        });

        $scope.country = $location.search()['country'];  // (1)
        $scope.$watch('country', function(newValue) {  // (2)
            $location.search('country', newValue);
        });
    }]);
</script>

String (1) 和 (2) 使 $scope.country 和 GET-param country 同步。 一切正常。但是当页面加载一些 GET 参数时,它不适用于 SELECT。 IE。 select 元素保持未selected。为什么?

您应该从国家/地区数组中搜索该参数,然后为国家/地区设置该对象 ID ng-model

$http.get('/api/countries/').success(function(data) {
    $scope.countries = data;
    if(country)
      $scope.country = ($filter('filter')($scope.countries ,{ name: $location.search()['country'] }))[0].id;
});

您应该在 URL 中传递 id 国家/地区,以便分配的值将正确绑定到 ng-options 模型值,并且您将在下拉列表中预填充值,您可能需要在 ng-options

中使用 track by id
ng-options="item.id as item.name for item in countries track by id"

这是生成的工作代码

<div ng-app="TourSearchApp">
    <form ng-controller="SearchFilterCtrl">
       <select ng-model="country" ng-options="item.id as item.name for item in countries">
            <option value="">Choose country</option>
        </select>
    </form>
</div>

<script>
    var app = angular.module('TourSearchApp', []);

    app.controller('SearchFilterCtrl', ['$scope', '$http', '$location', '$filter', function($scope, $http, $location, $filter) {        
        $http.get('/api/countries/').success(function(data) {
            $scope.countries = data;
            // validate raw GET-param
            $scope.country = $filter('filter')(data, {id: $scope.country}).length ? $scope.country : null;
        });

        // convert string to number!
        $scope.country = +$location.search()['country'];
        $scope.$watch('country', function(newValue) {
            $location.search('country', newValue);
        });
    }]);
</script>