让[OO]对象angularjs $资源返回的数组 [英] Make angularjs $resource return array of [OO] objects
问题描述
如何让angularjs $资源返回来自指定的域对象原型衍生/对象的数组?
How to make angularjs $resource return an array of objects derived/prototyped from specified domain object?
下面是 http://plnkr.co/edit/AVLQItPIfoLwsgDzoBdK的例子吗? p = preVIEW 用于处理一组注意
的S对象。
Here is an example on http://plnkr.co/edit/AVLQItPIfoLwsgDzoBdK?p=preview that processes a set of Note
s objects.
app.controller('MainCtrl', function($scope, NoteResource) {
$scope.name = 'World';
$scope.notes = NoteResource.query();
$scope.spellCheckAllNotes = function() {
angular.forEach($scope.notes, function(note) {
note.spellCheck();
});
}
});
问题是,$资源回报率资源
取值阵列,而不是注数组
s的资源
方法加入到原型。
The issue is that $resource returns array of Resource
s and not an array of Note
s with Resource
methods added to prototypes.
[解决方案应遵循良好的JavaScript做法]
[solution shall follow "good" javascript practices]
推荐答案
下面是完成的 plunker 。是生JSON解析成JSON对象。它使用 transformResponse
由阿曼多提及。
Here is the completed plunker. Yes raw json is parsed to JSON object. It is using transformResponse
as mentioned by Armando.
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;
}
]);
为了显示标题不从原始资源的使用,我修改标题
到 noteTitle
在注意
和HTML。
这篇关于让[OO]对象angularjs $资源返回的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!