簡介
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配置詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答