此篇關(guān)于AngularJS ui-sref的簡單使用,最近剛好學(xué)習(xí),就順便發(fā)到隨筆上了
具體用法:
<a ui-sref="man">男人</a>
這是一個(gè)非常簡單的ui-sref的使用,當(dāng)JavaScript重新生成網(wǎng)頁時(shí),它會(huì)查找$state中名為“man”的state,讀取這個(gè)state的url,然后在a標(biāo)簽里生成href="url" rel="external nofollow" ,
結(jié)果為: <a ui-sref="man" href="#/man.html" rel="external nofollow" >男人</a>
但如果,你在創(chuàng)建一個(gè)導(dǎo)航控制器,里面有一個(gè)導(dǎo)航item的數(shù)組:
$scope.items = [ {state: "man", statePage: "man.html"}, {state: "womanMe", statePage: "woman.html"} ] 然后在html中使用repeat:
<li repeat="item in items"> <a ui-sref="{{item.statePage}}"><{{item.state}}</a> </li> ui-sref不支持動(dòng)態(tài)綁定,這樣的代碼會(huì)報(bào)錯(cuò)。sref中你只能使用state名,頂多加點(diǎn)參數(shù)。
這樣的話,你只能放棄sref,用回href綁定,你可以用$state.href來讀取state的url。
下面簡單介紹下ui-sref參數(shù)的傳遞
頁面寫法如下
<a ui-sref="man({id:1,name:2})" >按鈕</a> 路由里面配置:
$stateProvider.state('man', { url: '/man.html?id&name', //參數(shù)必須先在這邊聲明 templateUrl: '../man.html', }) 點(diǎn)擊連接后,瀏覽器的地址則會(huì)變?yōu)椋?man.html/id=1&name=2
或者也可以這樣
$stateProvider.state('man', { url: '/man.html', templateUrl: '../man.html', params: {'id': null,'name':null},//參數(shù)在這邊聲明 }) 然后在對(duì)應(yīng)的controller里面通過$stateParams取值:$stateParams.id,$stateParams.name
其實(shí)ui-sref和$state.go本質(zhì)上是一個(gè)東西,可以看看ui-sref源碼
element.bind("click", function(e) { var button = e.which || e.button; if ( !(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || element.attr('target')) ) { var transition = $timeout(function() { // HERE we call $state.go inside of ui-sref $state.go(ref.state, params, options); }); 以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持錯(cuò)新站長站。
新聞熱點(diǎn)
疑難解答
圖片精選