通过$ resource angualrjs获取有关条件的数据

时间:2016-03-30 13:46:44

标签: angularjs node.js express angular-resource

我正在使用$ resource服务进行我的crud操作现在我想获取数据,例如获取约会的开始日期是今天。我正在通过

获取所有数据
vm.appointments = AppointmentsService.query();

我的服务代码是

    (function () {
  'use strict';

  angular
    .module('appointments')
    .factory('AppointmentsService', AppointmentsService);

  AppointmentsService.$inject = ['$resource'];

  function AppointmentsService($resource) {
    return $resource('api/appointments/:appointmentId', {
      appointmentId: '@_id'
    }, {
      update: {
        method: 'PUT'
      }
    });
  }
})();

现在我可以在此代码块AppointmentsService.query({condition});中给出条件,或者在node rest API中更改我的服务。 如果是,那么我的AppointmentsService.query会是什么电话

2 个答案:

答案 0 :(得分:2)

对于不同的网址路径,您可以创建如下所示的新方法,也可以将startDate作为查询字符串传递

控制器

路径参数

 vm.appointments = AppointmentsService.searchByDate({date:'03/30/2016'});

对于查询参数

vm.appointments = AppointmentsService.searchByDate({StartDate:'03/01/2016',EndDate:'03/30/2016'});

<强>服务

 function AppointmentsService($resource) {
    return $resource('api/appointments/:appointmentId', {
      appointmentId: '@_id'
    }, {
      update: {
        method: 'PUT'
      },
      // For Path Param
      searchByDate :{
        method : 'GET',
        url : 'your url/:date'
      },
     // For Query Param
      searchByDate :{
        method : 'GET',
        url : 'your url/:startDate/:endDate' ,
        params : { startDate : '@StartDate', endDate : '@EndDate' } 
      }
    });
  }

答案 1 :(得分:1)

更新您的服务代码......

 (function () {
     'use strict';

  angular
    .module('appointments')
    .factory('AppointmentsService', AppointmentsService);

  AppointmentsService.$inject = ['$resource'];

  function AppointmentsService($resource) {
    var service = {
        get: $resource('api/appointments/:appointmentId',{
           appointmentId: '@_id'
        },{
           method:'GET'
        }),
        update: $resource('api/appointments/:appointmentId',{
           appointmentId: '@_id'
        },{
           method:'PUT'
        }),
        query:$resource('api/appointments',{
           method:'GET',
           isArray:true
        })
        queryByStartDate:$resource('api/appointments/:startDate',{
           startDate: '@_startDate'
        },{
           method:'GET',
           isArray:true
        })
    }
    return service;
   }
})();

并在控制器

中调用queryByStartDate
var startDate = new Date(); //you can use $filter to format date
$scope.appointments = AppointmentsService.queryByStartDate({startDate:startDate});