当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > 详解AngularJS ui-sref的简单使用

详解AngularJS ui-sref的简单使用

2018年04月30日  | 移动技术网IT编程  | 我要评论

此篇关于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); 
   }); 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网