生活随笔
收集整理的這篇文章主要介紹了
angular $resource参数占位符释疑
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
在angular文檔關(guān)于$resource一節(jié)中,有如下用例:
var CreditCard = $resource('/user/:userId/card/:cardId',{userId:123, cardId:'@id'}, {charge: {method:'POST', params:{charge:true}}});
其中第二行讓人疑惑,@id是什么意思,文檔沒有過多解釋,說明這個(gè)問題太簡單了,肯定是我想岔了,經(jīng)過簡單測試,第二行中“cardId:'@id'"的解釋應(yīng)為:
cardId是resource的URL中的參數(shù)名,而@id表示參數(shù)對(duì)象中的名字,等于是把參數(shù)的id字段賦值給了url中的cardId參數(shù)。見示例:
form:<form ng-submit="submit()" class="form-inline"><label>username:</label><input type="text" ng-model="user.username"><label>name:</label><input type="text" ng-model="user.displayname"><input type="submit" value="submit" class="btn btn-primary"><input type="reset" value="reset" class="btn btn-inverse"></form> //route:
var app = angular.module('demo',['ngResource']);app.config(['$routeProvider',function($routeProvider){$routeProvider.when('/users',{templateUrl:'views/users.html',controller:userlistctrl})//用戶列表.when('/user/add',{templateUrl:'views/userinfo.html',controller:userctrl})//添加用戶.when('/user/add/:id',{templateUrl:'views/userinfo.html',controller:userctrl})//添加用戶.otherwise({redirectTo:'/'})//默認(rèn)}]);//controller:
function userctrl($scope,$http,$routeParams,$resource,userService){if($routeParams.id){//edit$scope.submit=function(){ userService.add({abc:$routeParams.id});};}else{//add}
}//service:
app.service('userService',function ($resource){var self=this;self.add=function(item){var res = $resource('/users/add/:test',{test:'@abc'});res.save(item);};self.list=function(){return $resource('/users').query();};
});//server:
app.all('/users/add/:test',function(req,res){res.send(200,req.params.test);
});
用“添加用戶”的功能作演示,訪問:http://localhost:3000/#/user/add/123,經(jīng)route解析到控制器userctrl
然后點(diǎn)submit提交表單,調(diào)用了userService服務(wù)的add方法,傳入了{(lán)adc:123}這個(gè)對(duì)象
再來看userService,$resource('/users/add/:test',{test:'@abc'})
意思就是把參數(shù)中的abc取出來賦值給test,我們的參數(shù)是{abc:123},所以自然而然服務(wù)器會(huì)接到一個(gè)post請(qǐng)求:http://localhost:3000/users/add/123
服務(wù)器是用test接的,打印出來,123無誤
總結(jié)
以上是生活随笔為你收集整理的angular $resource参数占位符释疑的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。