AngularJS - 始终将参数作为资源的默认值

时间:2012-08-20 08:22:04

标签: javascript angularjs

基本上我有一个场景,我访问的API在很多情况下使用:groupId作为url的一部分。有没有一种简单的方法可以避免在每个函数调用中传递$ routeParams.groupId?

var app = angular.module('plunker', []);

app.config(["$routeProvider", function($routeProvider) {
  $routeProvider.
    when("/:groupId/location", {templateUrl: "partials/location.html", controller: "LocationCtrl"});
}]);

/* Controllers */
app.controller('LocationCtrl', function($scope, $routeParams, Location) {
  Location.groupId = $routeParams.groupId; /* Is this even possible? I want to have it available to Location instead of the below*/
  Location.query();

  Location.query({groupId: $routeParams.groupId});
});

/* Services */
app.service("Location", function($resource, $routeParams) {
  return $resource("/api/:groupId/location", {}, {
    query: {method: "GET", isArray: true}
  });
});

2 个答案:

答案 0 :(得分:2)

我认为你可以这样做:

 app.service("Location", function($resource, $routeParams) {
    return $resource("/api/:groupId/location", {groupId:12345}, {
         query: {method: "GET", isArray: true}
    });
 });

我还没有测试过,但我相信这是文档的读取方式

答案 1 :(得分:0)

如果有任何帮助,由于上述答案对我不起作用,我将.query添加到通话结束处。

app.service("Location", function($resource, $routeParams) {
    return $resource("/api/:groupId/location", {groupId:'@groupId'})
                                                  .query({ groupId: 12345 });
 });