.save和$ save之间的差异在angularjs中的资源

时间:2014-02-07 13:17:14

标签: angularjs angular-resource

我看到代码都将$savesave调用为角度为$的资源。

有什么区别,你什么时候使用?

2 个答案:

答案 0 :(得分:15)

最佳解释===示例:

// by writing '{ id: '@id' }' we want the id to be taken from 'id' parameter in request data, hence the '@' sign. Note that this mechanism is available for non-GET RQs only:
var Notes = $resource('/notes/:id', { id: '@id' });

var noteId = "my_note1";
// below we specify 'id' explicitly - has to be done for GET RQ:
// operations on our note are done inside callback function, just to make sure that the note is resolved:
var note = Notes.get({ id: noteId }, function () {

    // let's make some changes:
    note.topic = "A brand new topic here!";

    // save using $resource "static" action (aka "class" action). 'id' is taken from data object:
    Notes.save(note);
    // We can overwrite 'id' just like this: 
    Notes.save({ id: "some_other_noteId" }, note);

    // even more changes:
    note.body = "Blah blah blah, new boring body is here";

    // this time save using instance action. Again: 'id' is taken from data object:
    note.$save();
    // changing id with instance action? there you go:
    note.$save({ id: "yet_another_noteId" });

    // Naturally, we could just:
    note.id = "OMG_how_many_of_those_noteIds_has_he_left";
    Notes.save(note);
    // ... and with instance action:
    note.id = "OK_he_wins";
    note.$save();
});

即使自定义$resource操作(由您定义)也有$ - 前缀对等项,只要它们不是GET - 请参阅http://docs.angularjs.org/api/ngResource.$resource#example_creating-a-custom-put-request
不,并非所有操作都有实例方法版本。在实例上调用GET会有什么意义?来自官方ngResource文档:

  

可以使用以下参数调用类对象或实例对象上的操作方法:

     
      
  • HTTP GET“class”操作:Resource.action([parameters],[success],[error])
  •   
  • 非GET“类”操作:Resource.action([parameters],postData,[success],[error])
  •   
  • 非GET实例操作:实例。$ action([参数],[成功],[错误])
  •   

答案 1 :(得分:0)

$save$resource的操作添加的方法。 save可以是特殊资源的方法。

所有操作都有$个前缀方法。在此处阅读更多内容:http://docs.angularjs.org/api/ngResource。$ resource