使angularjs $resource返回[OO]对象的数组

前端之家收集整理的这篇文章主要介绍了使angularjs $resource返回[OO]对象的数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何使angularjs $resource返回从指定域对象派生/原型化的对象数组?

以下是http://plnkr.co/edit/AVLQItPIfoLwsgDzoBdK?p=preview上处理一组Notes对象的示例.

  1. app.controller('MainCtrl',function($scope,NoteResource) {
  2. $scope.name = 'World';
  3. $scope.notes = NoteResource.query();
  4.  
  5. $scope.spellCheckAllNotes = function() {
  6. angular.forEach($scope.notes,function(note) {
  7. note.spellCheck();
  8. });
  9. }
  10. });

问题是$resource返回的是Resources数组,而不是添加了原型的Resource方法的Notes数组.

[解决方案应遵循“好”的JavaScript实践]

这是完成的 plunker.是原始json被解析为JSON对象.它正在使用Armando提到的transformResponse.
  1. app.factory('NoteResource',['$resource',function($resource) {
  2. var res = $resource('http://okigan.apiary.io/notes/:id',{},{
  3. query: {
  4. method: 'GET',params: {
  5. },isArray: true,transformResponse: function(data,header){
  6. //Getting string data in response
  7. var jsonData = JSON.parse(data); //or angular.fromJson(data)
  8. var notes = [];
  9.  
  10. angular.forEach(jsonData,function(item){
  11. var note = new Note();
  12. note.noteTitle = item.title;
  13. notes.push(note);
  14. });
  15.  
  16. return notes;
  17. }
  18. }
  19. });
  20. return res;
  21. }
  22. ]);

只是为了显示未使用原始资源的标题,我在note和html中将标题修改为noteTitle.

猜你在找的Angularjs相关文章