2013-11-14 28 views
4

感谢SO社区的一些很好的帮助,我有一个工作角度SPA,使用ui-router库使用多个状态/视图。不过,我得到的行为似乎与angular-ui-router文档不一致。角度ui路由器onEnter功能没有射击

从自己的文件约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正在被击中。我误解了文档吗?

Here is a long-awaited fiddle来演示。只需在Firebug/chrome devtools中显示控制台,您将看到缺少控制台输出。

任何帮助将是伟大的。我使用angular 1.2和ui-router 0.2.0。提前致谢!

+0

这将是一个更容易调试工作示例(即Plunkr)。 –

+0

@NateAbele对不起,花了这么长时间,但任何有兴趣的人都可以找到小提琴。谢谢! – tengen

+0

您也可以考虑使用[$ scope events](http://stackoverflow.com/questions/16094940/what-is-the-lifecycle-of-an-angularjs-controller)而不是使用路由器之一。 –

回答

20

两件事情:

  • onEnter方法适用于状态,不意见。您的定义中包含一个状态和三个视图,出于某种原因,您尝试将URL附加到您的视图中。

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