如何使用$ resource service获取具有该集合的对象。
我创建了一个服务来调用API端点。该服务以此格式返回JSON数据。但Angular永远不会用数据填充$ scope。我在这里添加了控制器的服务以及我如何使用它。我有一个非常类似的服务正在运行,但API正在返回集合,其中返回此API的是带有集合的对象。
JSON
{
"Url": "http://localhost:52882/api/metrics",
"MetricsCount": 10,
"Metrics": [{
"Url": "http://localhost:52882/api/metrics/1",
"Id": 1,
"Name": "3DRange",
"Description": "3-D range from shooter to target at time of launch",
"Unit": "Feet"
}]
}
SERVICE
(function () {
var metricRepository = function ($resource) {
var getMetricsFunc = function () {
var apiUri = "http://localhost:52882/api/metrics";
return $resource(apiUri).get();
};
return {
getMetrics: getMetricsFunc
};
};
var module = angular.module("dataCollectModule");
module.factory('metricRepository', metricRepository);
}());
CONTROLLER
'use strict';
(function () {
var DataCollectionSetupController = function ($scope, metricRepository, participantRepository) {
$scope.groupId = 1;
$scope.metrics = metricRepository.getMetrics();
$scope.metricscount= metricRepository.getMetrics().MetricsCount;
}
var app = angular.module("dataCollectModule");
app.controller("DataCollectionSetupController", DataCollectionSetupController);
}());
HTML Use fragment
<td>
{{metricscount}}
<select id="metricSelector" style="width: 100%;">
<option ng-repeat="metric in metrics" value="{{metric.Id}}">{{metric.Name}}</option>
</select>
</td>
答案 0 :(得分:0)
请在此处查看工作演示http://plnkr.co/edit/xdkp0Qk0cjcvWaTULbXy?p=preview
确保: 1.你可以参考 angular-resource.js
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-resource.js"></script>
2.将 ngResource 注入dataCollectModule
var app = angular.module('dataCollectModule', ['ngResource']);
3.在您的HTML更改ng-repeat="metric in metrics"
至ng-repeat="metric in metrics.Metrics"
<option ng-repeat="metric in metrics.Metrics" value="{{metric.Id}}">{{metric.Name}}</option>