angularjs 控制器实例化,ui-router [英] angularjs controller instantiation, ui-router
问题描述
控制器什么时候被实例化?你是第一次访问那个州吗?另外,当你重新访问状态时会发生什么,一个新的控制器是否再次被实例化?
When do controllers get instantiated? Is it the first time you visit that state? also, What happens when you revisit the state, does a new controller get instantiated again?
假设我有两个状态,A 和 B,并且我在状态 B 的顶部放置了一条警报语句.我注意到如果从状态 A 转到 B 状态 B 的警报语句会触发,这告诉我控制器得到了实例化.但是假设我从状态 A 到 B 到 C 再回到 B,警报语句不会发出.但是,如果我从状态 A 到 B 再到 C 到 B 再到 A 到 B,警报语句会再次响起.
Assume that I have two states, A and B, and I put an alert statement at the top of state B. I noticed that if go from state A to B state B's alert statement sets off which tells me that the controller got instantiated. But suppose I go from state A to B to C and back to B, the alert statement does NOT go off. However, if I go from state A to B to C to B to A to B the alert statement goes off again.
这是我的部分路线:
状态 A = app.login
state A = app.login
状态 B = app.pincodeCreate
state B = app.pincodeCreate
状态 C = app.messagelist
state C = app.messagelist
.run ($ionicPlatform, startup) ->
$ionicPlatform.ready(startup.ionicReady)
.config (googleAnalyticsCordovaProvider, $stateProvider, $urlRouterProvider) ->
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'AppController'
})
.state('app.pincodeCreate', {
url: '/pincode',
views: {
menuContent: {
templateUrl: 'templates/pincode.html',
controller: 'PincodeController'
}
}
})
.state('app.login', {
url: '/login',
views: {
menuContent: {
templateUrl: 'templates/login.html',
controller: 'LoginController'
}
}
})
.state('app.messagelist', {
url: '/messagelist',
views: {
menuContent: {
templateUrl: 'templates/messagelist.html',
controller: 'MessageListController',
resolve: {
activities: (utils, store, $state) ->
utils.getActivities().then ((activities) ->
store.isUserLoggedIn(true)
activities
), (error) ->
$state.reload()
}
}
}
})
推荐答案
当您从该状态的层次结构树之外的状态转到该状态或其后代之一时,该特定状态的视图控制器将运行.
The view's controller for a particular state runs when you go from state outside of the hierarchy tree of that state to that state or one of its descendants.
换句话说,如果您有以下层次结构:
In other words, if, say, you have the following hierarchy:
A B
/ /
AA C
/ \
C1 C2
然后,从 A 切换到 B 会实例化 B.然后切换到 C(或者 C1 或 C2,就此而言),然后再切换回 B,不会重新实例化 B 的控制器.
Then, switching from A to B would instantiate B. Switching then to C (or C1 or C2, for that matter), and then back to B, would not re-instantiate B's controller.
如果切换到 A(或 AA),则 A 将实例化.然后切换回 B 会重新实例化 B.
If you switch to A (or AA), then A would instantiate. Then switching back to B would re-instantiate B.
因此,在您的情况下,C 很可能是 B 的子状态.A 和 B 位于不同的祖先树中.
So, most likely in your case, C is a child state of B. And A and B are in separate ancestry trees.
这篇关于angularjs 控制器实例化,ui-router的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!