当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > AngularJS入门教程一:路由用法初探

AngularJS入门教程一:路由用法初探

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

本文实例讲述了angularjs路由用法。分享给大家供大家参考,具体如下:

目前的理解中,这个ng的路由模块可以用于带有多视图的单页面开发。

先把所有代码贴出:

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里面有许多属性。里面可以设置控制器,控制器会匹配给对应的字段或文件。就像上面代码中listcontroller控制器一样。

ng-view指令有许多规则:

在匹配路由时:

1、创建一个新的当前作用域。
2、删除前一个作用域。
3、将当前的模板(控制器等)与当前新建的作用域关联起来。
4、如果有内置关联的控制器,将其与当期作用域关联起来。

更多关于angularjs相关内容感兴趣的读者可查看本站专题:《angularjs指令操作技巧总结》、《angularjs入门与进阶教程》及《angularjs mvc架构总结

希望本文所述对大家angularjs程序设计有所帮助。

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

相关文章:

验证码:
移动技术网