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

时间:2015-08-04 20:18:12

标签: javascript angularjs select location ng-options

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

{{1}}

String(1)和(2)使$ scope.country和GET-param国家同步。 一切正常。但是当页面加载了一些GET-param时,它不适用于SELECT。 即select元素保持未选中状态。为什么呢?

2 个答案:

答案 0 :(得分:1)

您应该从countries数组中搜索该参数,然后为国家/地区ng-model

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

您应该在网址中传递id国家/地区,以便将指定的值正确绑定到ng-options模型值,并且您将获得预填充内部值的下拉菜单,您可能需要使用{{ 1}}在track by id

ng-options

答案 1 :(得分:0)

以下是生成的工作代码

<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>