我有父级组件:
(function () {
angular.module('app.module')
.component('parentComponent', {
templateUrl: 'parent.html',
controllerAs: 'vm',
controller: function ($scope) {
this.$onInit = () => {
$scope.parentData = 'test'
}
})
})()
子组件
(function () {
angular.module('app.module').component('childComponent', {
templateUrl: 'child.html',
controllerAs: 'vm',
controller: function () {
this.$onInit = () => {
}
}
})
})()
parent.html
<child-component></child-component>
child.html
<p>{{parentData}}</p>
因此,我想访问子组件中的parentData以便在子组件中显示字符串“ test”。我该怎么做?我阅读了一些有关绑定的内容,但是在此示例中我不知道如何使用它。
感谢您的任何建议。
答案 0 :(得分:2)
使用单向<
绑定:
<child-component in-data="$ctrl.parentData"></child-component>
子组件:
app.component("childComponent", {
bindings: {
inData: '<',
},
template: `
<div>{{$ctrl.inData}}</div>
`,
})
演示
angular.module("app",[])
.component("parentComponent", {
template: `
<fieldset>
Inside parent component<br>
parentData={{$ctrl.parentData}}
<child-component in-data="$ctrl.parentData"></child-component>
</fieldset>
`,
controller: function () {
this.$onInit = () => {
this.parentData = 'test'
};
},
})
.component("childComponent",{
bindings: {
inData: '<',
},
template: `
<fieldset>Inside child component<br>
inData={{$ctrl.inData}}
</fieldset>
`,
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<parent-component>
</parent-component>
<body>
有关更多信息,请参见
答案 1 :(得分:0)
您可以通过父控制器访问父数据,因为可以在组件声明中使用require:
这里是一个例子:
app.component('childComponent', {
require: {
parentCtrl: '^parentComponent'
},
controller: function() {
var self = this;
this.$onInit = function() {
self.parentCtrl.anyData;
};
}
});
看看codelord.net - Advanced Angular 1.x: Component Communication with Require
如果不需要父控制器,则可以将数据绑定到子组件:请参考@georgeawg答案