【问题标题】:AngularJS UI-Router event when changing route更改路由时的AngularJS UI-Router事件
【发布时间】:2015-04-11 21:20:13
【问题描述】:

使用 ngRoute 一次可以连接事件:$routeChangeStart 并执行不同的操作...

 app.run(function ($rootScope, $location) {
    $rootScope.$on("$routeChangeStart", function (event, next, current) {
    ................

是否可以使用 UI-Router 实现相同的功能?

【问题讨论】:

    标签: angularjs angularjs-routing


    【解决方案1】:

    是的,有可能:

    $rootScope.$on("$stateChangeStart",
        function (event, toState, toParams, fromState, fromParams) {
    

    【讨论】:

    • 每次路由改变时都会调用这个吗?或者应用程序第一次运行的任何时候?
    • @Notflip 每次状态改变前
    • 我最终不得不使用$stateChangeSuccess,因为$stateChangeStart 上的东西还没有完全准备好,但感谢它让我到达了我需要去的地方。
    【解决方案2】:

    或者直接使用

    $scope.$on("$stateChangeStart",...);
    

    如果您希望在单个页面上触发。

    【讨论】:

      【解决方案3】:

      在此处查看此答案,这是解决问题的正确方法。删除所有侦听器可能会产生未知的影响,因为可能在其他地方添加了侦听器。您需要删除您添加的那个,而不是全部。

      检查这个问题:Angular $rootScope $on listeners in 'destroyed' controller keep running

      为了完整性,这里也复制代码:

      animateApp.controller('mainController', function($scope, $rootScope, service) {
          $scope.pageClass = 'page-home';
          var unregister = $rootScope.$on('service.abc', function (newval) {
              console.log($scope.$id);
          });
          $scope.$on('$destroy', unregister);
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-24
        • 2016-05-25
        • 1970-01-01
        • 2020-03-17
        • 2017-09-15
        相关资源
        最近更新 更多