当前位置: 移动技术网 > IT编程>开发语言>JavaScript > ui-router使用详解

ui-router使用详解

2018年01月22日  | 移动技术网IT编程  | 我要评论
Angularjs ui-router - 组件:

官网原话:0.2.x状态事件已被弃用。我们建议转移到Transition Hooks,因为它们提供更多的灵活性,支持异步,并提供实现有意义的应用程序行为所需的上下文(Transition等)。

例如:下面这个例子已被废弃($stateNotFound等也被废弃)

$rootScope.$on('$stateChangeStart', function(event, transition) {
  event.preventDefault();
  // transitionTo() promise will be rejected with
  // a 'transition prevented' error
})

不要紧

angularjs提供了$locationChangeStart,$locationChangeSuccess方法同样可以用来监听URL的变化

//中文网例子
(function(){
     angular.module('Demo', [])
     .controller('testCtrl',["$location","$scope",testCtrl]);
     function testCtrl($location,$scope) {
        var url = "https://example.com:8080/#/some/path?foo=bar&baz=xoxo#hashValue";
        $location.absUrl();// https://example.com:8080/#/some/path?foo=bar&baz=xoxo#hashValue
        $location.url();// some/path?foo=bar&baz=xoxo
        $location.protocol();// http
        $location.host();// example.com
        $location.port();// 8080
        $location.path();// /some/path
        $location.search();// {foo: 'bar', baz: 'xoxo'}
        $location.search('foo', 'yipee');
        $location.search();// {foo: 'yipee', baz: 'xoxo'}
        $location.hash();// #hashValue
        $scope.$on("$locationChangeStart", function () {
          //监听url变化,在变化前做想要的处理
        });
        $scope.$on("$locationChangeSuccess", function () {
          //监听url变化,在变化后做想要的处理
        });
     }
  }());
var app = angular.module('myApp', ['ui.router']);
app.config(["$stateProvider", "$urlRouterProvider", function($stateProvider, $urlRouterProvider) {
    $stateProvider.state("index", {
        url: "/index",
        templateUrl: "/index" // 必须包含
    }).state("test1", {
        //abstract: true,// 设置为true时,只能被继承不能直接切换到此state
        url: "/test1",
        templateUrl: "/test/test1" // 必须包含
    }).state("test1.detail", {
        url: "/detail",
        templateUrl: "/test/test1"
    }).state("test1.info", {
        url: "/info",
        templateUrl: "/test/test2"
    }).state("test2", {
        url: "/test2",
        templateUrl: "/test/test2",
        //进入页面时会走该方法
        onEnter: function() {
            console.log('enter');
        },
        //离开时走该方法
        onExit: function() {
            console.log('exit');
        }
    }).state("test3", {
        url: "/test3",
        templateUrl: "/test/test3"
    })
    //1.当前的路径,2.需要重定向到的路径
    //$urlRouterProvider.when('', '/test3');
    $urlRouterProvider.otherwise("/test3");
}]);

app.run(function($rootScope, $location, $state) {
    $rootScope.$on("$locationChangeStart", function() {
        //监听url变化,在变化前做想要的处理
        console.log($location.path());
    });
    //提供全局的路由跳转方法
    $rootScope.goTo = function(page){
        $state.go(page);//page为state不是url,例如:test2
    }
});

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网