角度 ui 路由器 onEnter 函数未触发



感谢SO社区的一些大力帮助,我有一个工作的角度SPA,它使用ui路由器库使用多个状态/视图。但是,我得到的行为似乎与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()调用中看到的那样,我的期望是,当主状态加载时,我将开始看到他们从控制台消息中触发的所有状态/视图的列表。但是,仅记录来自home状态onEnter事件的第一条entered home state消息。没有一个其他观点的onEnter受到打击。我是否误读了文档?

这是一个期待已久的小提琴来演示。只需在Firebug/chrome开发工具中显示控制台,您就会看到缺少控制台输出。

任何帮助都会很棒。我正在使用角度 1.2 和 ui-router 0.2.0。提前感谢!

两件事:

  • onEnter方法适用于状态,而不是视图。您的定义中有一个状态和 3 个视图,并且出于某种原因,您尝试将 URL 附加到您的视图。

  • 为了进入一个状态,首先必须退出它。(A)你永远不会真正离开home状态(因为你只有一个状态定义),所以你永远无法重新进入它。(B) 看来您实际上是在尝试在 home 中创建子状态。即使您修复了语法,它仍然不起作用,因为当您进入父级的子状态时,通过更改为同一父级中的不同子状态,您仍然从未真正离开父状态,因此不会重新触发onEnter

我用过

 $state.reload();

在我的情况下触发承诺响应中的更新以解决此问题。你也可以做

$state.reload()
$state.go("statename")

这就是我解决它的方式。

看这里: https://github.com/angular-ui/ui-router/wiki/Quick-Reference#statereload

最新更新