45.angular路由设置

转自:https://www.cnblogs.com/best/tag/Angular/

AngularJS 路由也可以通过不同的模板来实现。

$routeProvider.when 函数的第一个参数是 URL 或者 URL 正则规则,第二个参数为路由配置对象。

路由配置对象语法规则如下:

$routeProvider.when(url, {
    template: string,
    templateUrl: string,
    controller: string, function  array,
    controllerAs: string,
    redirectTo: string, function,
    resolve: object<key, function>
});

参数说明:

  • template:

    如果我们只需要在 ng-view 中插入简单的 HTML 内容,则使用该参数:

    .when('/computers',{template:'这是电脑分类页面'})
  • templateUrl:

    如果我们只需要在 ng-view 中插入 HTML 模板文件,则使用该参数:

    $routeProvider.when('/computers', {
        templateUrl: 'views/computers.html',
    });

    以上代码会从服务端获取 views/computers.html 文件内容插入到 ng-view 中。

  • controller:

    function、string或数组类型,在当前模板上执行的controller函数,生成新的scope。

  • controllerAs:

    string类型,为controller指定别名。

  • redirectTo:

    重定向的地址。

  • resolve:

    指定当前controller所依赖的其他模块。

实例

 1 <html>
 2 <head>
 3 <meta http-equiv="content-type" content="text/html; charset=UTF-8">
 4 <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
 5 <script src="http://apps.bdimg.com/libs/angular-route/1.3.13/angular-route.js"></script>
 6 
 7 <script type="text/javascript">
 8 angular.module('ngRouteExample', ['ngRoute'])
 9 .controller('HomeController', function ($scope, $route) { $scope.$route = $route;})
10 .controller('AboutController', function ($scope, $route) { $scope.$route = $route;})
11 .config(function ($routeProvider) {
12     $routeProvider.
13     when('/home', {
14         templateUrl: 'embedded.home.html',
15         controller: 'HomeController'
16     }).
17     when('/about', {
18         templateUrl: 'embedded.about.html',
19         controller: 'AboutController'
20     }).
21     otherwise({
22         redirectTo: '/home'
23     });
24 });
25 </script>
26 
27   
28 </head>
29 
30 <body ng-app="ngRouteExample" class="ng-scope">
31   <script type="text/ng-template" id="embedded.home.html">
32       <h1> Home </h1>
33   </script>
34 
35   <script type="text/ng-template" id="embedded.about.html">
36       <h1> About </h1>
37   </script>
38 
39   <div> 
40     <div id="navigation">  
41       <a href="#/home">Home</a>
42       <a href="#/about">About</a>
43     </div>
44       
45     <div ng-view="">
46     </div>
47   </div>
48 </body>
49 </html>

转载于:https://www.cnblogs.com/sharpest/p/8177048.html

原文地址:https://www.cnblogs.com/twodog/p/12137757.html