1. 程式人生 > >AngularJS之頁面跳轉Route

AngularJS之頁面跳轉Route

AngulagJs的頁面使用Route跳轉

1.除了引用AngularJs.js外,還要引用路由JS, "~/Scripts/angularjs/angular-route.js"

2.通過$routeProvider定義路由,示例

複製程式碼
var testModule = angular.module('testModule', ['ngRoute']);

testModule.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/2', {//'/2'定義的路由路徑,以後通過此路徑訪問,通常定義為短路徑
templateUrl: "/home/index2",//"/home/index2"是路由實際訪問的路徑,可以是asp.net mvc的訪問路徑(如此例),也可是具體的頁面路徑,如“test/test.html" controller:'testController'//路由跳轉的controller,後面必須定義此控制器 }); $routeProvider.when('/3', { templateUrl: "/home/index3", controller:'testController' }) }]);
複製程式碼

3.使用路由跳轉,結合ng-view做spa

3.1  在JS中使用$location進行跳轉,如示例,在需要的時候呼叫goToIndex2即可

testModule.controller("testController", ["$scope", "$location", function ($scope, $location) {

    $scope.goToIndex2 = function () {
        $location.path("/2")
    }
}]);

  3.2 在html程式碼中使用href="#path"來進行跳轉

複製程式碼
<html >
<head>
    <
meta name="viewport" content="width=device-width" /> <title>Index1</title> @Styles.Render("~/Content/css/base") @Scripts.Render("~/script/base") <script src="~/scripts/ngmoudle/app.js"></script> </head> <body> <div ng-app="testModule" ng-controller="testController"> <header> <h1>This is Index1</h1> <button type="button" class="btn btn-default" ng-click="goToIndex2()">Index2</button> <a href="#/3" class="btn btn-default">Index3</a><!--通過heft="#path"方式進行跳轉--> <a href="#/2" class="btn btn-default" >Index2</a> </header> <div ng-view> </div> <footer>PAGE FOOTER</footer> </div> </body> </html>