本文實例講述了AngularJS路由用法。分享給大家供大家參考,具體如下:
目前的理解中,這個NG的路由模塊可以用于帶有多視圖的單頁面開發(fā)。
先把所有代碼貼出:
HTML:
<!doctype html><meta charset="UTF-8"><html><head> <link href="self.css" rel="external nofollow" rel="stylesheet"></head><body ng-app='routingDemoApp'><h2>AngularJS 路由應用</h2><ul> <li><a href="#/" rel="external nofollow" >首頁</a></li> <li><a href="#/computers" rel="external nofollow" >電腦</a></li> <li><a href="#/user" rel="external nofollow" >用戶</a></li> <li><a href="#/blabla" rel="external nofollow" >其他</a></li></ul><div ng-view></div><script src="angular.min.js"></script><script src="angular-route.min.js"></script><script src="test.js"></script></body></html>
list.html:
<div> <h1>HI,這里是list.html</h1> <h2>{{name}}</h2></div>JS:
var app = angular.module('routingDemoApp',['ngRoute']);app.config(['$routeProvider', function($routeProvider){ $routeProvider .when('/',{template:'這是首頁頁面'}) .when('/computers',{ template:'這是電腦分類頁面' }) .when('/user',{templateUrl:'list.html',controller:'listController'}) .otherwise({redirectTo:'/'});}]);app.controller('listController',function($scope){ $scope.name="ROSE";});首先由于我用的是Angular1.5,所以需要額外引入angular-route.js:
<script src="angular.min.js"></script><script src="angular-route.min.js"></script>
要使用NG里的路由,必須先在特定的模塊中定義它:
.config(['$routeProvider', function($routeProvider){//內容}通過when和otherwise兩個方法來進行路由的匹配。(其實就是匹配上面URL后面/的字符)。最后把匹配到的字符所對應的字段或者文件放入帶有ng-view 指令的DOM里面。
when里面有許多屬性。里面可以設置控制器,控制器會匹配給對應的字段或文件。就像上面代碼中l(wèi)istController控制器一樣。
ng-view指令有許多規(guī)則:
在匹配路由時:
1、創(chuàng)建一個新的當前作用域。
2、刪除前一個作用域。
3、將當前的模板(控制器等)與當前新建的作用域關聯起來。
4、如果有內置關聯的控制器,將其與當期作用域關聯起來。
更多關于AngularJS相關內容感興趣的讀者可查看本站專題:《AngularJS指令操作技巧總結》、《AngularJS入門與進階教程》及《AngularJS MVC架構總結》
新聞熱點
疑難解答
圖片精選