angularjs - UI-Router 父状态可以访问它的子成员吗?
问题描述
我正在使用 AngularJS 的UI-Router来管理我的 Web 应用程序的路由。
我有两种状态:parent_state
并child_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
抽象状态的控制器甚至从未被调用过。
这个问题涉及一个相关主题。但它没有告诉我如何在父状态的模板中显示子状态的参数。
解决方案
我想到的第一件事是在子参数更改后使用事件通知父母。请参阅以下内容(您甚至可以在此处运行它)。
渲染后,子级使用更改的参数值向父级发出事件。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>
推荐阅读
- python - python tkinter接口如何创建一个新的显示txt文件
- python-3.x - 如何使用漂亮的汤从这个 html 代码中刮取年份
- nginx - nginx 中的 map 指令仅适用于第一个变体
- reactjs - 使用带有上下文的 React Hook
- python - 带有字符串 Python 的 KeyError
- r - 如何使用 dplyr 按组减去值(减去存储为一组的空白)?
- android - RecyclerView 和 onTouch() 高亮,从详情活动返回列表时如何移除?
- python - 获取两个列表的差异,其中包含 dict
- mysql - Spring Data:如何更新具有唯一约束的子列表
- json - Flutter Google Maps Polyline - 参数类型“LatLng”无法分配给参数类型“List”
'