让[OO]对象angularjs $资源返回的数组 [英] Make angularjs $resource return array of [OO] objects

查看:187
本文介绍了让[OO]对象angularjs $资源返回的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何让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 Notes 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 Resources and not an array of Notes 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆