ngRoute路由改变监听事件(1)+ui.router状态路由

1.1、路由改变监听事件(1)
1、 $routeChangeStart:路由开始切换

2、 $routeChangeSuccess:路由切换成功

3、 $routeChangeError:路由切换失败(比如resolve中有错误),都会导致路由切换失败

4、 $locationChangeStart:当$location.path或$location.url发生变化时触发

5、 $locationChangeSuccess: 当$location.path或$location.url发生成功后触发

例子:
angular. module( 'myApp',[ 'ngRoute'])
    .config([ '$routeProvider', function ( $routeProvider) {
        $routeProvider
            . when( '/home',{
                templateUrl 'home.html',
                controller 'HomeController',

                /**
                 * 该属性的特点:列表(对象中的key值)可以注入到控制器中使用,
                 * 如果key值为字符串,那么服务名必须是字符串,
                 * 如果是函数,那么服务名必须是函数参数
                 */
                // resolve: {
                //     //这里的b值必须是服务的名字
                //     a: 'b'
                // }
            })
            . when( '/other',{
                templateUrl 'other.html',
                controller 'OtherController'
            })
            . otherwise( '/home');
    }])
    . run([ '$rootScope', function ( $rootScope) {

        //路由开始切换
        /**
         * args[0]: 事件
         * args[1]: 要切换的路由
         * args[2]: 第一次进入该方法,没有当前路由,为undefined
         */
        $rootScope. $on( '$routeChangeStart', function ( event, next, current) {
            console. log([ event, next, current]);
        });

        //路由切换成功
        /**
         * args[0]: 事件
         * args[1]: 当前的路由
         * args[2]: 上一个路由,第一次进入该方法,没有上一个路由,为undefined
         */
        $rootScope. $on( '$routeChangeSuccess', function ( event, current, previous) {
            console. log([ event, current, previous]);
        });

        //路由切换失败(比如resolve中有错误等待),都会导致路由切换失败
        $rootScope. $on( '$routeChangeError', function ( event, msg) {
            console. log([ event, msg]);
        });

        //当$location.path发生变化或者$location.url发生变化时触发
        $rootScope. $on( '$locationChangeStart', function ( event, msg) {
            console. log([ event, msg]);
        });

        //当且仅当path或url变化成功后触发
        $rootScope. $on( '$locationChangeSuccess', function ( event, msg) {
            console. log([ event, msg]);
        });

    }])
    .controller( 'HomeController',[ '$scope', '$location', function ( $scope, $location) {
        $scope. toOtherView  = function () {
            $location. path( '/other');
        }
    }])
    .controller( 'OtherController',[ '$scope', '$location', function ( $scope, $location) {
        $scope. toHomeView  = function () {
            $location. path( '/home');
        }
    }]);



1.2、切换路由时,控制器会被销毁,控制器会痛过$broadcast传播一个名字为$destory的消息,在自己的作用域中可以监听到此消息,在控制器中我们可以做一些清理工作,比如关闭一些定时器等
例子:
angular. module( 'myApp',[ 'ngRoute'])
    .config([ '$routeProvider', function ( $routeProvider) {
        $routeProvider
            . when( '/home',{
                templateUrl 'home.html',
                controller 'HomeController'
            })
            . when( '/other',{
                templateUrl 'other.html',
                controller 'OtherController'
            })
            . otherwise( '/home');
    }])
    . run([ '$rootScope', function ( $rootScope) {
       
    }])
    .controller( 'HomeController',[ '$scope', '$location', function ( $scope, $location) {
        $scope. toOtherView  = function () {
            $location. path( '/other');
        }
    }])
    .controller( 'ChildController',[ '$scope', '$interval', function ( $scope, $interval) {
       
        $scope.num  0;
        var interval  $interval( function () {
            $scope.num ++;
            console. log(num);
        }, 1000);


        /**
         * 切换路由时,控制器会被销毁
         * 控制器会通过$broadcast传播一个名字为$destroy的消息
         * 在自己的作用域中可以监听到这则消息,在控制器中我们就可以做一些清理工作,比如关闭定时器等
         */
        $scope. $on( '$destroy', function () {
            console. log( '父控制器死了');
            $interval. cancel(interval);
        });
    }])
    .controller( 'OtherController',[ '$scope', '$location', function ( $scope, $location) {
        $scope. toHomeView  = function () {
            $location. path( '/home');
        }
    }]);



2.1、ui.router状态路由

要下载angular-ui-router.js后引入方可使用
痛过$stateProvider与$urlRouterProvider两个服务使用

$stateProvider服务中有state属性选择状态变化
$urlRouterProvider服务为其他情况下的壮态(意外跳转)
例子:
angular. module( 'myApp',[ 'ui.router'])
    .config([ '$stateProvider', '$urlRouterProvider', function ( $stateProvider, $urlRouterProvider) {
        $stateProvider
        /**
         * 第一个参数是状态,不是路由,一般情况下名字和路由名字一样
         * 
         * ui-router是ng-route的一个升级版,基于状态机来组织接口,而不是简单的URL,基于ngRoute的,
         * 能否完成一些场景的功能(有很多优秀的特性,比如ui-view嵌套,ngRoute无法实现ui-view嵌套),尤其在手机上
         * 
         */
            . state( 'home',{
                //路由,这里的用法基本与ngRoute一样
                url '/home',
                templateUrl 'home.html',
                controller '',
                resolve {
                   
                }
            })
            . state( 'other',{
                url '/other',
                templateUrl 'other.html'
            })
        //意外跳转
        /**
         * ngRoute默认跳转路由'/',如果when方法中有'/'路由,不写意外跳转也会跳转
         */
        $urlRouterProvider. otherwise( '/home');
    }])


2.2、意外跳转的方式
1、直接跟路由路径

2、直接跟一状态

3、返回一函数

4、返回两个参数

5、返回两个参数,后一个为函数

6、.rule函数中返回一个函数

例子:
angular. module( 'myApp',[ 'ui.router'])
    //uiRouter 理念: 管理状态, 路由辅助
    .config([ '$stateProvider', '$urlRouterProvider', function ( $stateProvider, $urlRouterProvider) {
        $stateProvider
            . state( 'home',{
                url '/home',
                templateUrl 'home.html'
            });

        //意外跳转的方法
        // $urlRouterProvider.otherwise('/home');
        // $urlRouterProvider.otherwise('home');

        // $urlRouterProvider.otherwise(function ($injector,$location) {
        //     $location.path('/home');
        // });

        /**
         * 第一个参数: 给空字符串,想要匹配的入口路径
         * 第二个参数: 重新指向的路由
         */
        // $urlRouterProvider.otherwise('','home');

        /**
         * 如果第二个参数是函数,需要返回路由路径
         */
        // $urlRouterProvider.otherwise('',function () {
        //     return 'home';
        // });

        $urlRouterProvider. rule( function ( $injector, $location) {
            return  '/home';
        });
    }]);


2.3、状态路由的resolve属性与factory配置服务获取数据处理
resolve属性的特点:列表中(对象中的key值)可以注入到控制器中使用;如果key值是字符串,那么注入的服务名必须是该字符串;如果key值是函数,那么注入的服务名必须是函数的参数
例子:
angular. module( 'myApp',[ 'ui.router'])
    .config([ '$stateProvider', '$urlRouterProvider', function ( $stateProvider, $urlRouterProvider) {
        $stateProvider
            . state( 'home',{
                url '/home',
                templateUrl 'home.html',
                controller 'HomeController',
                resolve {
                    myFoo 'foo',

                    //在这里,我们可以用到上面的属性,这里和ngRoute里面不一样,上面的key就是服务的名字
                    getName : function ( myFoo) {
                        return  myFoo.name;
                    },
                   
                    /**
                     * 如果返回的对象是一个promise,那么该对象会在控制器实例化之前解析完数据
                     * @param $http
                     * @returns {*}
                     */
                    setHttp : function ( $http) {
                        return  $http({
                            url 'data/news.json',
                            method 'get'
                        });
                    },
                    getData : function ( setHttp) {
                        return  setHttp. data;
                    }
                }
            })
            . state( 'other',{
                url '/other',
                templateUrl 'other.html'
            })
        $urlRouterProvider. otherwise( '/home');
    }])
    . factory( 'foo', function () {
        return {
            name 'zs',
            age 12
        }
    })
    .controller( 'HomeController',[ '$scope', 'myFoo', 'getName', 'setHttp', 'getData', function ( $scope, myFoo, getName, setHttp, getData) {
        // console.log(myFoo);
        // console.log(getName);
        console. log( setHttp. data);
        console. log( getData);
    }]);

2.4、state中的模版属性解析

如果写了views属性:template与templateUrl就会失效

例子:
angular. module( 'myApp',[ 'ui.router'])
    .config([ '$stateProvider', '$urlRouterProvider', function ( $stateProvider, $urlRouterProvider) {
        $stateProvider
            . state( 'index',{
                url '/index',
                abstract : true,
                templateUrl 'index.html',
                //如果写了views属性,template和templateUrl会失效
                views {
                    home {
                        templateUrl 'home.html'
                    },
                    other {
                        templateUrl 'other.html'
                    }
                }
            })
        $urlRouterProvider. otherwise( '/index');
    }])


2.5、state中的abstract属性

设置改模版为抽象模版
如果值为true,表示抽象模版永远不会被激活,但是可以设置为被激活的字节点,可以使包装器包含

例子
angular. module( 'myApp',[ 'ui.router'])
    .config([ '$stateProvider', '$urlRouterProvider', function ( $stateProvider, $urlRouterProvider) {
        $stateProvider
            . state( 'tab',{
                url '/tab',
                //abstract为true,表示抽象模版永远不能被激活,但是可以设置为被激活的子节点,可以使包装器包含
                abstract : true,
                templateUrl 'tab.html'
            })
            . state( 'tab.news',{
                url '/news',
                templateUrl 'news.html'
            })
            . state( 'tab.live',{
                url '/live',
                templateUrl 'live.html'
            })
            . state( 'tab.talk',{
                url '/talk',
                templateUrl 'talk.html'
            })
            . state( 'tab.mine',{
                url '/mine',
                templateUrl 'mine.html'
            });
        $urlRouterProvider. otherwise( '/tab/news');
           
    }])


2.6、state状态路由中传递参数的方法

区分传递参数与接受参数的对应格式

例子:
angular. module( 'myApp',[ 'ui.router'])
    .config([ '$stateProvider', '$urlRouterProvider', function ( $stateProvider, $urlRouterProvider) {
        $stateProvider
            . state( 'home',{
                url '/home',
                templateUrl 'home.html',
                controller 'HomeController'
            })
            . state( 'other',{

                // url: '/other',
                // url: '/other/:name',
                // url: '/other/{name}',

                //跟正则针对$location服务
                // url: '/other/{name: [0-9]}',

                //查询参数,这样写暴露在地址栏中不安全
                // url: '/other?name',

                /**
                 * 一般传参数,这样传,参数写在params(参照post请求)
                 */
                url '/other',
                params {
                    name '',
                    id ''
                },

                templateUrl 'other.html',
                controller 'OtherController',

                //进入页面时会走该方法
                onEnter : function () {
                    console. log( 'enter');
                },
                //离开时走该方法
                onExit : function () {
                    console. log( 'exit');
                }

            });
        $urlRouterProvider. otherwise( 'home');
    }])
    .controller( 'HomeController',[ '$scope', '$location', '$state', function ( $scope, $location, $state) {
        $scope. toOtherView  = function () {
            //跟的是路由
            // $location.path('/other/zs');
            //跟的是状态
            // $state.go('other',{name: 23});

            // $location.path('/other/123');

            //查询参数
            // $location.url('/other?name=123');

            $state. go( 'other',{name 23});
        }
    }])
    .controller( 'OtherController',[ '$scope', '$location', '$state', '$stateParams', function ( $scope, $location, $state, $stateParams) {
        $scope. goBack  = function () {
            $state. go( 'home');
        }
        console. log( $stateParams.name)
    }])








  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值