【问题标题】:How to get access to resource URL params with ngResource?如何使用 ngResource 访问资源 URL 参数?
【发布时间】:2014-02-20 00:49:47
【问题描述】:

我有一个使用 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>

【问题讨论】:

    标签: javascript angularjs angularjs-resource


    【解决方案1】:

    这样的事情看起来还可以吗?

    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>
    

    【讨论】:

      【解决方案2】:

      只需将区域 ID 放在范围内,例如:$scope.aid = $routeParams.aid;,然后在您想要的任何地方引用它。当您使用单个 aid 进行查询时,所有建筑物都不是相同的吗?

      【讨论】:

      • 是的,你是对的,我可能会尝试做类似的事情。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-15
      • 1970-01-01
      • 2015-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-24
      相关资源
      最近更新 更多