如何使用ngResource访问资源URL参数?

时间:2014-02-19 13:45:29

标签: javascript angularjs angularjs-resource

我使用ngResource:

处理建筑物的AngularJS服务
angular.module('neighborhoodApp')
  .factory('Building', function ($resource) {
    return $resource('/areas/:aid/buildings/:id', {
      'id': '@_id'
    });
  });

在我的一个观点中,我列出了建筑物:

$scope.buildings = Building.query({
  aid: $routeParams.aid
});

请注意,我从路线获取区域ID,但此信息未存储在我的模型中。

我的问题是,当我展示我的建筑物时,我想使用区域ID,但我无法访问它:

<div ng-repeat="building in buildings">
  {{building | json}}
  <!-- 'building' doesn't include the area id
       I can't modify the server response and somehow
       I shouldn't have to, the information is inside the URL of the query()
       Can I get URL params from the resource instance? -->
</div>

2 个答案:

答案 0 :(得分:0)

这样的东西好吗?

<强>的Javascript

//Service
angular.module('neighborhoodApp')
      .factory('Building', function($resource) {
        return {
            query: function(id) {
                aid: id,
                resource: $resource('/areas/:aid/buildings/:id', {
                    'id': id
                });
            }
        }
});

// Invokation
$scope.buildings = Building.query({
  aid: $routeParams.aid
});

<强> HTML

<pre>AREAID: {{ buildings.id }}</pre>
<div ng-repeat="building in buildings.resource">
  {{building | json}}
</div>

答案 1 :(得分:0)

只需将区域ID放在范围内,例如:$scope.aid = $routeParams.aid;,并在任何地方引用它。当您使用单aid查询时,所有建筑物都不一样吗?