2014-02-07 27 views

回答

13

最好的解釋===例如:

// 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動作(由您定義)有自己的$ -prefixed同行,只要他們不GET - 。見http://docs.angularjs.org/api/ngResource.$resource#example_creating-a-custom-put-request
不,並非所有操作都有實例方法版本。在實例上調用GET會有什麼意義?從官方ngResource文檔:

類對象或實例對象上的動作的方法可以使用以下參數來調用:

  • HTTP GET「類」動作:Resource.action([參數]非GET GET「類」操作:Resource.action([參數],postData,[成功],[錯誤])
  • 非GET實例操作:實例。$ action ([參數],[成功],[錯誤])
0

$save是通過$resource的動作添加的方法。保存可以是特殊資源的一種方法。

所有操作都有$前綴方法。在這裏閱讀更多:http://docs.angularjs.org/api/ngResource $資源