初学AngularJs路由(一)

来源:互联网 发布:blued软件免费下载 编辑:程序博客网 时间:2024/04/28 08:15

目前的理解中,这个NG的路由模块可以用于带有多视图的单页面开发。
先把所有代码贴出:
HTML:

<!doctype html><meta charset="UTF-8"><html><head>    <link href="self.css" rel="stylesheet"></head><body ng-app='routingDemoApp'><h2>AngularJS 路由应用</h2><ul>    <li><a href="#/">首页</a></li>    <li><a href="#/computers">电脑</a></li>    <li><a href="#/user">用户</a></li>    <li><a href="#/blabla">其他</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、如果有内置关联的控制器,将其与当期作用域关联起来。

0 0
原创粉丝点击