当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > AngularJS之页面跳转Route实例代码

AngularJS之页面跳转Route实例代码

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

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>

 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(''); }]);

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

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

相关文章:

验证码:
移动技术网