AngularJS ui-sref的简单使用
具体用法:
<a ui-sref="man">男人</a>
这是一个非常简单的ui-sref
的使用,当JavaScript
重新生成网页时,它会查找$state
中名为“man”
的state
,读取这个state
的url
,然后在a
标签里生成href="url" rel="external nofollow"
,
结果为: <a ui-sref="man" href="#/man.html" rel="external nofollow" >男人</a>
但如果,你在创建一个导航控制器,里面有一个导航item的数组:
$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
不支持动态绑定,这样的代码会报错。sref
中你只能使用state
名,顶多加点参数。
这样的话,你只能放弃sref
,用回href
绑定,你可以用$state.href
来读取state
的url
。
下面简单介绍下ui-sref
参数的传递
页面写法如下
<a ui-sref="man({id:1,name:2})" >按钮</a>
路由里面配置:
$stateProvider.state('man', {
url: '/man.html?id&name', //参数必须先在这边声明
templateUrl: '../man.html',
})
点击连接后,浏览器的地址则会变为:/man.html/id=1&name=2
或者也可以这样
$stateProvider.state('man', {
url: '/man.html',
templateUrl: '../man.html',
params: {'id': null,'name':null},//参数在这边声明
})
然后在对应的controller
里面通过$stateParams
取值:$stateParams.id,$stateParams.name
其实ui-sref
和$state.go
本质上是一个东西,可以看看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);
});