angular + ui-router: $stateChangeSuccess 在状态 b 上触发但不在 a.b 上 [英] angular + ui-router: $stateChangeSuccess triggered on state b but not on a.b

查看:25
本文介绍了angular + ui-router: $stateChangeSuccess 在状态 b 上触发但不在 a.b 上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ui-router 0.2.11/AngularJS 1.3.0

ui-router 0.2.11 / AngularJS 1.3.0

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

I struggle to understand why my $stateChangeSuccess event handler in BarCtrl is not triggered on #/foo/bar. It is triggered on #/bar.

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

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

What I'm trying to achieve is that on #/foo/bar first FooCtrl's handler is triggered and then BarCtrl's:

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')
  });
});

推荐答案

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

While preparing a fiddle I came across my mistakes. I was thinking abstract views would not need a template since they cannot be accessed and assuming the template of foo's parent state would take over, which is not the case.

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

To achieve what I wanted I only had to add:

  template: '<ui-view />',

像这样:

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

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

这篇关于angular + ui-router: $stateChangeSuccess 在状态 b 上触发但不在 a.b 上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆