Anguler route(路由)初始

本文介绍了Angular中实现路由的详细步骤,包括引入路由JS文件、注入依赖、配置路由、定义路由展示区域以及实现路由导航。通过`$routeProvider`服务的`when()`和`otherwise()`方法设置路由规则,`ng-view`指令用于显示路由内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、路由: angular:vue react angular都是单页面应用程序, 利用a标签的锚点 功能,页面之前跳转都是通过路由实现

2、路由的实现:

        ①angular使用路由 需要引入js文件  
        ②注入依赖 var app=angular.module('app',['ngRoute']) ; 路由注入到主模型上
        ③使用路由 app.config() 里面注入服务  实现路由
        ④配置项 路由提供的服务  $routeProvider
            app.config(['$routeProvider',function($routeProvider){
                $routeProvider.when()
            }])
            (1)$routeProvider服务 提供两个方法
                  .when() ;//配置路由的名称
                  .otherwise();//重定向 页面路由不对的不对 重新定向

            (2) when('/名称',{//名称:使用英文  /home
                   template:'展示内容',
                   templateUrl:'展示内容',//路径
                   controller:['$scope',function($scope){

                      }]
                   })  
           (3) otherwise({ //重定向  304 302 303
                       redirectTo:'/home'
                  })
      ⑤路由展示
            <div ng-view></div>
      ⑥.路由导航
             <a href="#!/home">第一页</a>

eg:

    <ul>
         <li><a href="#!/home">首页</a></li>//#!/home阻止页面刷新,不刷新就能切换页面
         <li><a href="#!/news">新闻</a></li>
         <li><a href="#!/dong">动态</a></li>
    </ul>
     <!-- 显示内容   -->
    <div ng-view></div>
            var app=angular.module('app',['ngRoute']);
            app.controller('main',['$scope','$location',function($scope,$location){
                $location.path('/home')
            }])
            //路由
            app.config(['$routeProvider',function($routeProvider){
                $routeProvider
                .when('/home',{
                    // template:'<h2>首页数据{{msg}}</h2>',
                    // controller:['$scope',function($scope){
                    //     $scope.msg='哈哈哈123'
                    // }]
                    templateUrl:'view/home.html',
                    controller:['$scope',function($scope){
                        $scope.man='底下是一个数组',
                        $scope.arr=[1,2,3,4,3,2]
   
                    }]
                })
                .when('/news',{
                    template:'<h2>新闻</h2>',
                })
                .when('/dong',{
                    template:'<h2>动态</h2>'
                })
                .otherwise({
                    redirectTo:'/home'
                })
            }])

③home.html页面

<div>
    <h3>首页的内容</h3>
    <p>第一段:{{man}}</p>
    <ul>
        <li ng-repeat='inte in arr track by $index'>{{inte}}</li>
    </ul>
    <ul>
        <li ng-repeat=''></li>
    </ul>
</div>


               

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值