【问题标题】:How synchronize select and GET-param in AngularJS?如何在 AngularJS 中同步 select 和 GET-param?
【发布时间】:2015-10-27 09:41:20
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript angularjs select location ng-options


    【解决方案1】:

    您应该从国家/地区数组中搜索该参数,然后为国家/地区 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;
    });
    

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

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

    【讨论】:

    • @VictorBornov 很高兴看到它有帮助..谢谢 :)
    【解决方案2】:

    这是生成的工作代码

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

    【讨论】:

      猜你喜欢
      • 2012-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      • 2012-03-09
      • 1970-01-01
      相关资源
      最近更新 更多