属性/URL映射
AngularJS Resource:与 RESTful API 交互
自定义$resource方法
<!DOCTYPE html> <html ng-app="app"> <head> <meta charset="utf-8"> <title></title> </head> <body> <div ng-controller="controller"> <button ng-click="get()">get</button> <button ng-click="query()">query</button> <button ng-click="save()">save</button> <button ng-click="remove()">remove</button> <button ng-click="sendEmail()">sendEmail</button> </div> <script src="angular.js"></script> <script src="angular-resource.js"></script> <script> angular.module('app', ['ngResource']).controller('controller', ['$scope', 'Game', function($scope, Game) { $scope.get = function() { // data1.json?group=1&id=id // GET Game.get({ gameId: 'data1', id: 'id' }, function(resp) { console.log(resp) resp.name = 'jiji3' // data2.json?group=1 // POST // {id: "data2", name: "jiji3"} resp.$save() }, function(err) { console.log(err) }) } $scope.query = function() { // data1.json?group=1&id=id // GET Game.query({ gameId: 'data1', id: 'id' }) } $scope.save = function() { // data1.json?group=1&id=id // POST // {name: "Ari"} Game.save({ gameId: 'data1', id: 'id' }, { name: 'Ari' }) } $scope.remove = function() { Game.remove({}, { gameId: 'data1', id: 'data2' }) /* { gameId: 'data1', id: 'data2' } 这2个{}是数据 所以匹配@id */ } $scope.sendEmail = function() { Game.sendEmail({ id: 'data1' }) } }]).factory('Game', ['$resource', function($resource) { /** * $resource(url[, paramDefaults][, actions]); * If the parameter value is prefixed with @ then the value of that parameter is extracted from the data object * (useful for non-GET operations). */ return $resource('/test/test/:gameId.json', { gameId: '@id', group: '1' }, { sendEmail: { method: 'POST' } }) }]) </script> </body> </html>
data1.json
{ "id": "data2", "name": "jiji1" }
data2.json
{ "id": "data1", "name": "jiji2" }