boh*_*.be 5 angularjs angular-ui-router
我从angular-ui-router获得以下错误:
TypeError: Cannot read property '@' of null
...
TypeError: Cannot read property '@main' of null
...
Run Code Online (Sandbox Code Playgroud)
我已经对可能导致此错误的原因进行了一些研究,并得出结论,问题在于我在onEnter期间通过$ state.go(state)在条件为false时进行重定向另一个州
以下是关于github上同一问题的一些讨论:
我尝试了一些建议,但它们没有用.他们似乎没有提供解决方案,但只是指出问题,并根据这个 github讨论它应该解决,但我似乎无法让它工作.
我使用的是AngularJS v1.2.24和ui-router v0.2.11.
使用以下代码(简化):
.state('main', {
abstract: true,
url: '/main',
templateUrl: '/main/_layout.html'
})
.state('main.home', {
url: '/home',
templateUrl: '/main/home/home.html',
controller: 'HomeCtrl',
onEnter: function ($state)
{
if (condition === true){
$state.go('main.catch')
}
}
})
.state('main.catch', {
url: '/catch',
templateUrl: '/main/catch/catch.html',
controller: 'CatchCtrl'
})
Run Code Online (Sandbox Code Playgroud)
有没有办法让这个工作?或者我应该考虑一种完全不同的方法来实现相同的结果?
PS:可能的解决方法是在控制器中执行以下操作,
$scope.$on('$stateChangeSuccess', function(){
// conditional redirect here
}
Run Code Online (Sandbox Code Playgroud)
但我不想在HomeCtrl中这样做.
我也遇到过类似的情况,是这样解决的:
.state('main.home', {
url: '/home',
templateUrl: '/main/home/home.html',
controller: 'HomeCtrl',
onEnter: function ($state)
{
if (condition === true){
$timeout(function() {
$state.go('main.catch')
)};
}
}
})
Run Code Online (Sandbox Code Playgroud)
诀窍在于您希望让原始状态更改完成,而不是尝试在状态更改中间进行重定向。$timeout 允许原始状态更改完成,然后立即触发到所需状态的更改。