获取URL参数条件

时间:2015-08-07 03:54:19

标签: json angularjs parameters filter

如何为URL参数的名称和开始日期设置条件“过滤器”?我这里有一个工作代码。问题是,如果您键入名称搜索字段“名称”。开始日期也会给出一个值。我认为因为“&” delimeter绑定URL。任何人都有关于这里的建议吗?

    Name:<input type="text" class="form-control" ng-model="name" />
Start Date:<input type="text" class="form-control" ng-model="date" />
<button ng-click="search(name,date)" class="blue_button" >search</button>

功能:

    var myTable=angular.module('myTable',[]);
      myTable.controller('tableCtrl',function($scope,$http){
      $http.get("http://staging.api.sample.com/events.json", {headers: {Authorization: 'vuNYhXbpKfH73IjSw856PnGUyOAlmgTW'}})
       .success(function(response) {
          debugger
        $scope.members=response.events;
         $scope.totals = response.paging;
      });

    $scope.search=function(name,date){
         $http.get("http://staging.api.sample.com/events.json?name="+name+"&start_date_from="+date, {headers: {Authorization: 'vuNYhXbpKfH73IjSw856PnGUyOAlmgTW'}})
       .success(function(response) {

        $scope.members=response.events;
         $scope.totals = response.paging;
      });

      }
  });

2 个答案:

答案 0 :(得分:0)

当你要发起请求时,你可以使用字符串构建器吗?

$scope.search=function(name,date){
     var requestParams = '?';
     if(name) requestParams += "name= " + name;
     if(name && date) requestParams += "&"
     if(date) requestParams += "start_date_from=" + date;
     // you may want to remove the trailing & if date is not provided

     $http.get("http://staging.api.sample.com/events.json" + requestParams, {headers: {Authorization: 'vuNYhXbpKfH73IjSw856PnGUyOAlmgTW'}})
   .success(function(response) {

    $scope.members=response.events;
     $scope.totals = response.paging;
  });

  }

我还建议将数据调用拉入角度服务。

答案 1 :(得分:0)

使用提供$ resource对象的服务。

angular.module('myTable')
.factory('Api', function($resource) {
   var BASE_URL = 'http://staging.api.sample.com';

   var events = $resource(BASE_URL + '/events.json', {}, {
     get: {
       method: 'GET',
       cache: true,
       headers: {
         'Authorization': '....'
       }
     }
   });

   return {
     Events: events
   };
});

将服务添加为依赖项并设置可选参数。不会设置具有未定义值的参数(如果缺少名称,日期或两者)

angular.module('myTable')
.controller('tableCtrl',function($scope,$http, Api) {
   $scope.search=function(name,date) {
     Api.Events.get({
       'name': name,
       'date': date
     }).$promise.then(function(successResponse) {
         //Handle success here
     }, function(err) {
         //Handle error here
     });
   };
});

注意:angular.module('myTable',[])重新声明myTable模块。请参阅AngularJS module documentation的创建与检索部分。相关位:

  

请注意使用angular.module('myModule',[])将创建   模块myModule并覆盖任何名为myModule的现有模块。使用   angular.module('myModule')来检索现有模块