如何使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();
- });
- }
- });
问题是$resource返回的是Resources数组,而不是添加了原型的Resource方法的Notes数组.
[解决方案应遵循“好”的JavaScript实践]
这是完成的
plunker.是原始json被解析为JSON对象.它正在使用Armando提到的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;
- }
- ]);