如何使 angularjs $resource 返回从指定域对象派生/原型(prototype)化的对象数组?
这是 http://plnkr.co/edit/AVLQItPIfoLwsgDzoBdK?p=preview 上的示例处理一组 Note
s 对象。
app.controller('MainCtrl', function($scope, NoteResource) {
$scope.name = 'World';
$scope.notes = NoteResource.query();
$scope.spellCheckAllNotes = function() {
angular.forEach($scope.notes, function(note) {
note.spellCheck();
});
}
});
问题是 $resource 返回数组
Resource
s 而不是 Note
的数组与 Resource
添加到原型(prototype)的方法。[解决方案应遵循“好的”javascript实践]
最佳答案
这是完整的 plunker .是的,原始 json 被解析为 JSON 对象。它正在使用 transformResponse
正如阿曼多所说。
app.factory('NoteResource', ['$resource',
function($resource) {
var res = $resource('http://okigan.apiary.io/notes/:id', {}, {
query: {
method: 'GET',
params: {
},
isArray: true,
transformResponse: function(data, header){
//Getting string data in response
var jsonData = JSON.parse(data); //or angular.fromJson(data)
var notes = [];
angular.forEach(jsonData, function(item){
var note = new Note();
note.noteTitle = item.title;
notes.push(note);
});
return notes;
}
}
});
return res;
}
]);
只是为了显示原始资源中没有使用标题,我修改了
title
至noteTitle
在 Note
并在 html 中。
关于angularjs - 使 angularjs $resource 返回 [OO] 对象的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23523343/