当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > Angular路由ui-router配置详解

Angular路由ui-router配置详解

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

简介

angularjs自身提供路由ng-router,但是ng-router不是很好用,配置项零散,好比vue提供的组件传值一样,虽然提供给你了用法,但是开发过程中逻辑一多用着萌萌的,所以我们抛开ng-router来看ui-router。

引入ui-router

我们可以去bootcdn搜索ui-router,本地创建js文件,将代码copy进去使用,这样就可以打入本地使用了,但是要注意的是,angular的main.js一定要在ui-router之前引用,注意一下先后顺序问题。

例如:

<script src="angular.main.js"></script>
<script src="angular-ui-router.js"></script>

配置ui-router

 //angular.module("modulename",dep); 定义模块依赖(两个参数)
  //angular.module("modulename"); 获取模块 (一个参数)
  var app = angular.module("myapp",["ui-router"]);
  app.config(["$stateprovider","$urlrouterprovider",function($stateprovider){
      //app.config配置项
      //$stateprovider 状态供应商,(名字可以看出关于路由的一系列配置需要由$stateprovider完成)
      //$urlrouterprovider 路由重定向
      $stateprovider.state("home",{
        url: "/home"
        template: "<h1>首页</h1>"
      }) .state("about",{
          url: "/about"
          template: "关于我们"
      });
      $urlrouterprovider.otherwise("home")
  }])

页面配置

<div ui-view></div>  //相当于vue中的插槽,单页面应用切换路由用来显示当前路由界面
<a ui-sref="home">首页</a> //angular默认会转换为href
<a ui-sref="about">关于我们</a> //angular默认会转换为href

路由激活状态样式

ui-sref-active="active"

完整代码

<html ng-app="myapp">
<head>
<style>
.active{
color: red
}
</style>
<script src="angular.main.js"></script>
<script src="angular-ui-router.js"></script>
</head>
<body>
<div ui-view></div>
<footer>
<a ui-sref="home" ui-sref-active="active">首页</a>
<a ui-sref="about" ui-sref-active="active">关于</a>
<a ui-sref="items">商品</a>
</footer>
</body>
<script>
var app = angular.module("myapp", [ui-router]);            app.config(["$stateprovider","$urlrouterprovider",function($stateprovider){
$stateprovider.state("home",{
url: "/home"
template: "首页"
}) .state("about",{
url: "/about"
template: "关于我们"
}).state("items",{//牛逼的潜逃路由
url: "/items",
templateurl: "./items.html",
controller:["$scope",$state,function($scope,$state){
$scope.jump = function(){
$state.go("home");
}
$scope.jumpother = function() {
$state.go("items.phone",{
id: "phone"
});
}
}]
}).state("items.comp",{
url: "/comp",
template: "<h1>电脑商品</h1>"
}).state("item.phone",{
url:"phone/:id",
template:"<h1>手机商品</h1>",
controller:["$scope","$stateparams",function($scope,$stateparams){
console.log($stateparams);
}]
});
$urlrouterprovider.otherwise("home")
}
</script>
</html>

嵌套路由页面

      <div>
          <h1>商品展示</h1>
          <button ng-click="jump()">点击跳转首页</button>
          <a ui-sref="about">跳转至关于我们</a>
          <button ng-click="jumpother()">穿参数</button>
          <a ui-sref="items.other({id:"sref"})"></a>
          <ul>
              //因为我们外面父级路由是items所以自路由用items为前缀
            <li><a ui-sref="items.comp">电脑</a></li>
            <li><a ui-sref="items.phone">手机</a></li>
          </ul>
          <div ui-view></div>
      </div>  

总结

以上所述是小编给大家介绍的angular路由ui-router配置详解,希望对大家有所帮助

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

相关文章:

验证码:
移动技术网