【问题标题】:angular + ui-router: $stateChangeSuccess triggered on state b but not on a.bangular + ui-router: $stateChangeSuccess 在状态 b 上触发但不在 a.b 上
【发布时间】:2014-10-21 13:36:29
【问题描述】:

ui-router 0.2.11 / AngularJS 1.3.0

我很难理解为什么我在 BarCtrl 中的 $stateChangeSuccess 事件处理程序没有在 #/foo/bar 上触发。它在 #/bar 上触发。

#/foo/bar -> Console: foo
#/bar -> Console: bar

我想要实现的是在 #/foo/bar 上首先触发 FooCtrl 的处理程序,然后触发 BarCtrl 的:

foo
bar

我的代码:

var app = angular.module('foobar', ['restangular', 'ui.bootstrap', 'ui.router'])
app.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider.state('root', {
    url: "/",
    template: '<div ui-view></div>'
  })
  .state('foo', {
    abstract: true,
    url: "/foo",
    controller: 'FooCtrl',
  })
  .state('foo.bar', {
    url: "/bar",
    controller: 'BarCtrl',
  })
  .state('bar', {
    url: "/bar",
    controller: 'BarCtrl',
  });
})

app.controller('FooCtrl', function($scope) {
  $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
    console.log("foo");
  });
});

app.controller('BarCtrl', function($scope) {
  $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
    console.log('bar')
  });
});

【问题讨论】:

  • 确保BarCtrl#/foo/bar时被调用
  • @Alexei:你能解释一下吗?我在想 foo.bar 链中的所有控制器都会被调用,文档说:“当一个状态是“活跃的”时——它的所有祖先状态也都是隐式活跃的。'
  • 你能准备一把小提琴吗?我刚刚在本地检查了一下,一切都按预期工作。

标签: angularjs angular-ui-router


【解决方案1】:

在准备小提琴时,我发现了自己的错误。我在想抽象视图不需要模板,因为它们无法访问,并假设 foo 的父状态的模板将接管,但事实并非如此。

为了实现我想要的,我只需要添加:

  template: '<ui-view />',

像这样:

.state('foo', {
  abstract: true,
  url: "/foo",
  controller: 'FooCtrl',
  template: '<ui-view />',
})

相关讨论:https://github.com/angular-ui/ui-router/issues/325

【讨论】:

    【解决方案2】:

    您没有指定 #/foo/bar 的 url 是全部。

    您正在指定 foo.bar 的状态,但该状态只能从 #/bar 的 url 访问。

    更改以下内容...

      .state('foo.bar', {
        url: "/bar",
        controller: 'BarCtrl',
      })
    

    ...到...

      .state('foo.bar', {
        url: "/foo/bar",
        controller: 'BarCtrl',
      })
    

    ...你应该很好。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 2016-10-03
    相关资源
    最近更新 更多