Angular UI路由器如何重定向深层链接?

时间:2014-07-29 16:59:31

标签: angularjs angular-ui-router

我是Angular UI路由器的新手,我正在尝试了解如何阻止用户使用保存的超链接跳转到我的应用程序中间。我总是希望所有收藏夹或其他记忆的链接在最初访问网站时被迫运行代码运行。但是,如果他们通过应用程序菜单和标签访问该状态,我不想阻止用户进入该状态。

代码方面我要做的是强制链接到" / feature1 / subfeature1"到" /"在下面的状态树中,但仅当链接来自用户记忆的某个链接时。

$stateProvider
.state('main', {
  url: "/",
  templateUrl: "partials/main.html"
})
.state('feature1', {
  url: "/feature1",
  templateUrl: "partials/feature1.html"
})
.state('feature1.subfeature1', {
  url: "/feature1/subfeature1",
  templateUrl: "partials/feature1.subfeature1.html",
  controller: ......
  }
})

Angular UI路由器常见问题解答中有关于防止用户进入状态的部分,但是当我运行示例时,将为所有stateChangeStart事件调用事件处理程序,包括通过$ state.go()在应用程序内进行合法导航。我希望区分跳到应用程序中间的检测超链接和$ state.go(),因为我只使用$ state.go()来导航状态。代码方面我认为想要做类似下面的代码。但是,不知道什么代码进入"需要测试这里"。

 app.run(function($rootScope, $state,) {
   $rootScope.$on('$stateChangeStart', function(e, to) {

    var isDeepLink =  NEED TEST HERE 

    if (isDeepLink ) {
      e.preventDefault();
    // Optionally set option.notify to false if you don't want 
    // to retrigger another $stateChangeStart event
     $state.go("\");
    }
}
});

有什么想法吗?

谢谢,

杰里

2 个答案:

答案 0 :(得分:0)

如何创建一个注册应用程序是否已初始化的服务。在这个例子中,我将“app has initialized”定义为“已经调用了根状态的控制器”。

app.service("appInit", function() { 
    var done = false;
    return { 
        isDone: function() { return isinitialized; },  
        initDone: function() { isinitialized = true; }
    }
}

app.run(function($rootScope, $state, appInit) {
  $rootScope.$on('$stateChangeStart', function(e, to) {
  if (!appInit.isDone()) {
    e.preventDefault();
    // Optionally set option.notify to false if you don't want 
    // to retrigger another $stateChangeStart event
    $state.go("\");
  }
}

$stateProvider
.state('main', {
  url: "/",
  templateUrl: "partials/main.html",
  controller: function(appInit) { appInit.initDone(); }
})

编辑:一个更简单的解决方案:

这个更简单的解决方案有效,因为转换来自根状态(“”)的唯一时间是在应用首次加载时的初始转换期间。

app.run(function($rootScope, $state, appInit) {
  $rootScope.$on('$stateChangeStart', function(e, to, toParams, from) {
  if (from.name === "" && to.name !=== "main") {
    e.preventDefault();
    // Optionally set option.notify to false if you don't want 
    // to retrigger another $stateChangeStart event
    $state.go("\");
  }
}

答案 1 :(得分:-1)

如果它是深层链接,$stateChangeStart将始终触发

因此,此代码将按您的要求执行,

app.run(function($rootScope, $state,) {
  $rootScope.$on('$stateChangeStart', function(e, to) {
     // code here runs if it is not a deep link
  });
  // code here runs if its a deep link
}