我正在尝试使用 AngularJS 来检索 JSON 数组(字符串列表)。我创建了一个资源,如下所示:
packageResource.factory('Package', ['$resource', function($resource) {
return $resource('/static/package.json', {}, {
'get': {
method: 'GET',
transformResponse: function (data) {
return angular.fromJson(data)
},
isArray: true
}
});
}]);
我的控制器是这样的:
MainController = [
'$scope', 'Package', function($scope, Saved, Rules) {
$scope.package = (Package.get());
}
];
还有我的模板:
<ul>
<li ng-repeat="item in package">{{item}}</li>
</ul>
<p> {{package}}</p>
我希望它显示 package.json 数组中所有项目的列表,然后,为了测试,我添加了{{package}}
并希望它打印内容,但相反,我得到:
- {}
- {}
- {}
- {}
- {"0":"s","1":"r","2":"d"}
JSON 文件包含以下内容:
[1,3,6,"srd"]
但是,如果我将 package.json 更改为一个对象,它会完美运行。例如:
{
"author": "John",
"name": "project",
"version": 1
}
当然,更改isArray
为false
. 我得到:
- 约翰
- 项目
- 1
So it appears that something can't handle an array, and mangles it into an object. I am having trouble figuring out what - all the Angular documentation shows Resource and Scope working with arrays, and it doesn't make since for them not to. I explicitly added the isArray: true
flag to my Resource definition, but no luck.
I am using Angular version 1.0.8. I am a complete newbie, so it may be something painfully obvious, but I have been trying to get this to work for over a day now.