感谢SO社区的一些帮助,我有一个工作角度SPA,使用ui-router库使用多个状态/视图。但是我得到的行为似乎与angular-ui-router
文档不一致。
从他们关于onEnter的文档中,我希望无论何时我使用$state.go("home")
,与该状态的配置对象绑定的onEnter()
事件都会启动,但我看不到它发生。例如:
/* myApp module */
var myApp = angular.module('myApp', ['ui.router'])
.config(['$stateProvider', function ($stateProvider) {
$stateProvider.state('home', {
url: "/",
views: {
'top': {
url: "",
template: '<div>top! {{topmsg}}</div>',
controller: function ($scope) {
$scope.topmsg = "loaded top!";
console.log("top ctrl!");
},
onEnter: function () {
console.log("entered bottom state's onEnter function");
}
},
'middle': {
url: "",
template: '<div>middle! {{middlemsg}}</div>',
controller: function ($scope) {
$scope.middlemsg = "loaded middle!";
console.log("middle ctrl!");
},
onEnter: function () {
console.log("entered bottom state's onEnter function");
}
},
'bottom': {
url: "",
template: '<div>bottom! {{bottommsg}}</div>',
controller: function ($scope) {
$scope.bottommsg = "loaded bottom!";
console.log("bottom ctrl!");
},
onEnter: function () {
console.log("entered bottom state's onEnter function");
}
}
},
onEnter: function () {
console.log("entered home state");
}
});
}])
.controller('MyAppCtrl', function ($scope, $state/*, $stateParams*/) {
$scope.statename = $state.current.name;
$scope.testmsg = "app scope working!";
console.log("MyAppCtrl initialized!");
$state.go("home");
});
正如你可以从州的配置对象中的所有onEnter()
调用中看到的那样,我的期望是当家庭状态加载时,我会开始看到他们正在触发的所有状态/视图的列表他们的控制台消息但是,从entered home state
州的home
事件中仅记录了第一条onEnter
消息。没有一个其他视图的onEnter
被击中。我误读了文档吗?
Here is a long-awaited fiddle来证明。只需在firebug / chrome devtools中显示控制台,您就会看到缺少控制台输出。
任何帮助都会很棒。我正在使用角度1.2和ui-router 0.2.0。提前谢谢!
答案 0 :(得分:20)
两件事:
onEnter
方法适用于州,而非视图。您在定义中有一个州和三个观点,并且由于某种原因,您尝试将网址附加到您的观看次数。
为了输入州,首先必须退出。 (A)你实际上从未离开home
状态(因为你只有一个状态定义开始),所以你永远不能重新输入它。 (B)看来您实际上是在home
内创建子状态。即使您修复了语法,它仍然无法工作,因为当您输入父项的子状态时,通过更改为同一父项中的其他子状态,您仍然永远不会实际离开父状态,因此不会重新触发onEnter
。
答案 1 :(得分:1)
我用过
$state.reload();
在我的案例中触发承诺响应中的更新来解决此问题。你也可以
$state.reload()
$state.go("statename")
这就是我解决它的方式。
见这里:https://github.com/angular-ui/ui-router/wiki/Quick-Reference#statereload