oki*_*gan 5 angularjs angular-resource
如何使angularjs $ resource返回从指定域对象派生/原型化的对象数组?
以下是http://plnkr.co/edit/AVLQItPIfoLwsgDzoBdK?p=preview处理一组Notes对象的示例.
app.controller('MainCtrl', function($scope, NoteResource) {
$scope.name = 'World';
$scope.notes = NoteResource.query();
$scope.spellCheckAllNotes = function() {
angular.forEach($scope.notes, function(note) {
note.spellCheck();
});
}
});
Run Code Online (Sandbox Code Playgroud)
问题是$ resource返回Resources的数组,而不是Note带有Resource添加到原型的方法的s 数组.
[解决方案应遵循"好"的JavaScript实践]
dma*_*tro 10
这是完成的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;
}
]);
Run Code Online (Sandbox Code Playgroud)
只是为了显示未使用原始资源的标题,我修改title为noteTitlein Note和in html.
| 归档时间: |
|
| 查看次数: |
15875 次 |
| 最近记录: |