PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

AngularJS入门教程(1)-路由用法简单介绍

黄舟
黄舟 原创
2017-05-27 10:33:39 655浏览

这篇文章主要介绍了AngularJS路由用法,简单分析了AngularJS路由的概念、功能及基本使用方法,需要的朋友可以参考下

本文实例讲述了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>
<p ng-view></p>
<script src="angular.min.js"></script>
<script src="//m.sbmmt.com/m/faq/angular-route.min.js"></script>
<script src="test.js"></script>
</body>
</html>

list.html:

<p>
  <h1>HI,这里是list.html</h1>
  <h2>{{name}}</h2>
</p>

JS:

var app = angular.module('routingDemoApp',['ngRoute']);
app.config(['$routeProvider', function($routeProvider){
    $routeProvider
      .when('//m.sbmmt.com/m/',{template:'这是首页页面'})
      .when('/computers',{
        template:'这是电脑分类页面'
      })
      .when('/user',{templateUrl:'list.html',controller:'listController'})
      .otherwise({redirectTo:'//m.sbmmt.com/m/'});
}]);
app.controller('listController',function($scope){
  $scope.name="ROSE";
});

首先由于我用的是Angular1.5,所以需要额外引入angular-route.js:

<script src="angular.min.js"></script>
<script src="//m.sbmmt.com/m/faq/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入门教程(1)-路由用法简单介绍的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。