首页 > 解决方案 > UI-Router 父状态可以访问它的子成员吗?

问题描述

我正在使用 AngularJS 的UI-Router来管理我的 Web 应用程序的路由。

我有两种状态:parent_statechild_state排列如下图。

$stateProvider
.state('parent_state', {
    abstract: true,
    views: {
        '@' : {
            templateUrl: 'http://example.com/parent.html',
            controller: 'ParentCtrl'
        }
    }
})
.state('child_state', {
    parent: 'parent_state',
    url: '/child',
    params: {
      myArg: {value: null}
    },
    views: {
      'mainarea@parent_state': {
          templateUrl: 'http://example.com/child.html',
          controller: 'ChildCtrl'
        }
    }
})

从内部ChildCtrl,我可以myArg这样访问:

app.controller("ChildCtrl", function($stateParams) {
    console.log('myArg = ', $stateParams.myArg);
});

我是否可以访问myArg并将其显示在 html 页面中parent.html?如果是这样,怎么办?我看到ParentCtrl抽象状态的控制器甚至从未被调用过。

这个问题涉及一个相关主题。但它没有告诉我如何在父状态的模板中显示子状态的参数。

标签: angularjsangular-ui-router

解决方案


我想到的第一件事是在子参数更改后使用事件通知父母。请参阅以下内容(您甚至可以在此处运行它)。

渲染后,子级使用更改的参数值向父级发出事件。Parent 将其抓取并显示在自己的模板中。

angular.module('myApp', ['ui.router'])
.config(function ($stateProvider, $urlRouterProvider) {
  $stateProvider
  .state('parent_state', {
    abstract: true,
    template: "<h1>Parent! Value from child: {{ paramFromChild }}</h1><div ui-view></div>",
    controller: function ($scope) {
      $scope.$on('childLoaded', function (e, param) {
        $scope.paramFromChild = param;
      });
    }
  })
  .state('child_state', {
    parent: 'parent_state',
    url: '/child',
    params: {
        myArg: {value: null}
    },
    template: '<h2>Child! Value: {{ param }}</h2>',
    controller: function($stateParams, $scope){ 
      $scope.param = $stateParams.myArg;
      $scope.$emit('childLoaded', $stateParams.myArg);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.10/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.20/angular-ui-router.js"></script>

<div ng-app="myApp">
  <a ui-sref="child_state({myArg: 'first'})">First link</a>
  <a ui-sref="child_state({myArg: 'second'})">First second</a>
  <div ui-view></div>
</div>


推荐阅读