【发布时间】:2018-04-16 15:57:33
【问题描述】:
我有一些组件,它们共同构成了我的菜单。我想在最顶层的组件中获取一个参数,并在较低的组件中使用它。
我想将“app-rest”值传递给我的组件。
angular.module('app').component('application', {
controller: applicationController,
template: `
<cp-layout
config="$ctrl.config"
menu="$ctrl.menu"
clientId="$ctrl.clientId"
logout="$ctrl.logout()">
<div ui-view class="content-wrapper ng-scope ng-fadeInRight"></div>
</cp-layout>
`
});
applicationController.$inject = [ '$window', '$http', 'MensagemService', '$filter', 'Siseg' ];
function applicationController($window, $http, MensagemService, $filter, Siseg) {
const vm = this;
vm.$onInit = function() {
vm.clientId = 'app-rest';
}
这是 cp 布局:
(function() {
'use strict';
angular.module('cp.layout', ['cp.navbar', 'cp.sidebar'])
.component('cpLayout', {
bindings : {
config: '<',
logout: '&?',
menu: '<?',
menuFile: '<?',
clientId: '@'
},
replace: true,
transclude: true,
template : `
<div data-ng-class="{ 'layout-fixed' : $ctrl.config.layout.isFixed, 'aside-collapsed' : $ctrl.config.layout.isCollapsed, 'layout-boxed' : $ctrl.config.layout.isBoxed, 'layout-fs': $ctrl.config.layout.useFullLayout, 'layout-h': $ctrl.config.layout.horizontal, 'aside-float': $ctrl.config.layout.isFloat,'aside-toggled': $ctrl.config.layout.asideToggled}">
<cp-navbar config="$ctrl.config" logout="$ctrl.logout()"></cp-navbar>
{{$ctrl.clientId}} / Nothing is printed here.
<cp-sidebar class="aside lateral-sidebar" config="$ctrl.config" menu="$ctrl.menu" menu-file="$ctrl.menuFile" clientId="$ctrl.clientId"></cp-sidebar>
<div class="content-layer m-b-1">
<ng-transclude></ng-transclude>
</div>
</div>
`
});
})();
【问题讨论】:
-
为您的最顶层组件的定义添加一个名为
controllerAs: 'topCtrl'的属性(例如)并在childrend 中使用topCtrl.someProperty访问此控制器中的某些内容 -
@AdityaParab 组件默认将其控制器绑定到
$ctrl。有关详细信息,请参阅AngularJS Developer Guide - Directive Definition vs Component Definition -
是的.. 我知道这一点。从这个问题来看,尚不清楚需要从多少级访问数据。一方面,你的答案是正确的。但是对于有多个级别的场景,您可以覆盖
controllerAs的值,以便能够从任意数量的级别访问它的父控制器。
标签: angularjs angularjs-components