获取URL个参数条件

Get URL parameters condition

如何为 URL 参数的名称和开始日期设置条件 "filter"?我这里有一个工作代码。问题是,如果您键入名称搜索字段 "Name"。开始日期本身也会给出一个值。我认为是因为绑定 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;
      });

      }
  });

当您要触发请求时,您可以使用字符串生成器吗?

$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;
  });

  }

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

使用提供 $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 的创建与检索部分。相关位:

Beware that using angular.module('myModule', []) will create the module myModule and overwrite any existing module named myModule. Use angular.module('myModule') to retrieve an existing module