使用angular-resource
正如您在服務/工廠內說的那樣。它已經提供了很多你的要求:
myApp.factory("dataService", [
"$resource",
function ($resource) {
return $resource("http://someBaseUrl/:action/:id", {
id: "@id" // default parameters
},
{
// custom methods
update: { method: "PUT" },
doOtherStuff: { method: "GET", action: "DoOtherStuff" }
});
}
]);
的$resource
默認提供了以下REST兼容功能:
{
'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'}
};
你必須包括你自己的任何其他功能,如update
並在doOtherStuff
上面的例子。
:action
部分是一種簡單的方法來提供任何自定義操作,而不是REST兼容。
使用在控制器:
myApp.controller("myCtrl", [
"dataService",
function (dataService) {
// first parameter can be used for any extra query parameters
// second parameter always is a callback
var myData = dataService.query({}, function() {
// success
});
var mySingleInstance = dataService.get({ id: 12 });
this.doUpdate = function (entity) {
dataService.update(entity);
// Or, if the 'entity' is a resource entity:
// entity.$update();
}
this.customMethod = function() {
dataService.doOtherStuff();
}
}
]);
見https://docs.angularjs.org/api/ngResource/service/ $資源的完整文檔
看起來不錯。順便說一句,如何創建獨立的'指令'我在這裏試過這是不工作:http://jsfiddle.net/ydkezd15/7/ – 3gwebtrain
檢查此更新的jsfiddle http://jsfiddle.net/ydkezd15/8/ – devqon
但它依賴'app'變量正確嗎?我正在尋找'directive'如何轉換成像'component'一樣? – 3gwebtrain