如果$ state.name('某些东西')使用ui-router

时间:2014-08-05 10:42:20

标签: angularjs angular-ui-router

是否可以检查州名称,如果匹配则执行某些操作?

有点像这样:

.run(function ($rootScope, $state, $location, Auth) {
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState) {
      if($state.name == "popular") {
         // Do Something
      } else {
         // Do Something else
      }
    });
  });

我的目标是在用户从一个州登录到另一个州时重定向用户。

4 个答案:

答案 0 :(得分:3)

是的,你可以这样做:$state.includes("myState")

答案 1 :(得分:1)

尝试$state.current

var currentLocation= $state.current

console.log(currentLocation); 

您的currentLocation看起来像这样

Object {
    url: "/currentUrl", 
    templateUrl: "templates/currenthtml.html", 
    controller: "CurrentController", 
    name: "currentStateName"
}

然后

if(yourCondition){
----Do something----
}

答案 2 :(得分:1)

到目前为止提供的解决方案似乎略显扁平,如果您不考虑动态检查,则会引发一些可扩展性问题。发现自己做了几个不同的选择,可能还有一个更好的选择,但这是我用来检查动态ui-router数据的解决方案:

<强>控制器:

$scope.dynData = $stateParams.dynData || ''; // default value
if($scope.dynData === '') {
    return $state.go('wherever');
} else {
    return $state.go('wherever');
}

高级检查以防止子网址重定向:

// Check dynData value doesn't exist and that we're not trying to load a child state
$scope.dynData = $stateParams.dynData;
if($scope.dynData === '' && $scope.$state.$current.path.length === 2) {
    $state.go('wherever');
// If passed, dynData exists and insure we're not trying to load a child state
} else if($scope.$state.$current.path.length === 2) {
    $state.go('wherever');
}

<强>配置

.state('wherever', {
        url: '/videos/:dynData'

可能更干净/更清晰的方法,但它对我来说很有用。您可以记录范围状态并查找要检查的大量事项,路径长度恰好适用于我需要的逻辑。 添加默认值可以提供比未定义的更好的内容&#39;检查。

答案 3 :(得分:0)

你可以argv[1]