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 content="width=device-width" /> <title>Index1</title> @Styles.Render("~/Content/css/base") @Scripts.Render("~/script/base") <script src="https://www.jb51.net/~/scripts/ngmoudle/app.js"></script> </head> <body> <div ng-app="testModule" ng-controller="testController"> <header> <h1>This is Index1</h1> <button type="button" ng-click="goToIndex2()">Index2</button> <a href="#/3">Index3</a><!--通过heft="#path"方式进行跳转--> <a href="#/2" >Index2</a> </header> <div ng-view> </div> <footer>PAGE FOOTER</footer> </div> </body> </html>

4.关于Angularjs版本不得不说的问题(追加部分),“/"变”%2F”问题

新的项目直接使用Nuget获取Angularjs后,发现按照以上的写法,不能跳转了,表现症状为 <a href="#/2">Index2</a> 点击之后,发现浏览器地址变为“#%22”,“/"变”%2F”导致路由不能跳转了,一顿猛查和调试,才发现AngularJs自1.6版本后对地址做了特别处理 知道原因后,解决问题也很简单,在Angular中声明用回旧有方式即可。

可参见

testModule.config(['$locationProvider', function($locationProvider) { $locationProvider.hashPrefix(''); }]); testModule.config(['$locationProvider', function($locationProvider) { $locationProvider.hashPrefix(''); }]);

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwwfwy.html