将数组样式的查询参数传递给Angularjs中的资源

Passing array style query parameters to a resource in Angularjs

本文关键字:Angularjs 资源 查询 数组 样式 参数传递      更新时间:2023-09-26

我目前正在使用一个API,它使用数组样式的查询参数来过滤项,但我不太确定如何在Angular中实现这一点。

在下面的例子中,我有一个下拉列表,它采用了选择的ng模型,并将其应用于参数列表,然后激发一个方法来过滤我的列表。通常,在处理普通键值时,这很简单。然而,在这种情况下,URL需要以下内容:

example.com/api/list?filter[number]=1

我目前的设置看起来像

$scope.paramers = {
    include: 'playing', 
    sort: '-id'
};
$scope.refresh = function () {
    LFGFactory.query($scope.paramers, function success (response) {
        $scope.loading = true;
        var data = response.data;
        if (data.length >= 1) {
            $scope.rowList = data;
            $scope.loading = false;
        } else {
            $scope.loading = false;
        }
    },
    function err (data) {
        console.log(data);
    });
};

虽然我的观点看起来是这样的:

        <div class="form-group pull-right">
            <select id="plat-sel" name="plat-sel" class="form-control" ng-model="paramers.filter" ng-change="refresh()">
                <option value="" disabled selected>Filter by Platform</option>
                <option value="1183">Xbox One</option>
                <option value="1184">PlayStation 4</option>
                <option value="1182">PC</option>
                <option value="1188">Wii U</option>
                <option value="1186">Xbox 360</option>
                <option value="1185">PlayStation 3</option>
            </select>
        </div>

以下的工厂

  .factory('LFGFactory', function($resource) {
    var base = 'http://example.com/api/v1.0/';

    return $resource(base +'lfg', {},
        {
          update: {
            method: 'PUT',
            isArray: true
          },
          delete: {
            method: 'DELETE',
            isArray: true
          },
          query: {
            method: 'GET',
            isArray: false
          }
        }
    );
  }) 

通常情况下,如果我只想向现有的$scope.paramers对象添加filter:"1",这就可以了。然而,我需要以某种方式添加filter[number]=1。我该如何处理ng模型和我目前的设置?

查看您的LFGFactory服务:

angular.module('myApp').factory('LFGFactory', function($resource) { 
      var base = 'example.com/api/v1.0/';
      return $resource(base +'lfg', {}, 
            { update: { method: 'PUT', isArray: true }, 
              delete: { method: 'DELETE', isArray: true }, 
              query:  { method: 'GET', isArray: false } } 
      );
}) 

您正在使用ngParamSerializer

select元素更改为:

 <select id="plat-sel" name="plat-sel" class="form-control" 
          ng-model="paramers['filter[number]']" ng-change="refresh()">

JSFiddle