我需要在两个独立组件之间实现组件通信。 我使用了require关键字但是它会抛出错误
错误:$ compile:ctreq缺少必需的控制器
无法找到指令'ctwo'所需的控制器'锥'!
这是我的代码
@Override
public void handleIntent(Intent intent) {
}
angular.module("app", [])
.component('cone', {
template: '<p>Component one</p>',
controller: function() {
console.log("component one loaded")
this.fone = function() {
console.log("component one function one")
}
}
})
.component('ctwo', {
template: '<p>Component two</p>',
controller: function() {
console.log("component two loaded")
},
require: {
cone: 'cone'
}
})
答案 0 :(得分:3)
对于组件2调用组件1函数,您需要使组件2成为组件1的子组件。在组件1模板中或通过包含:
angular.module("app", [])
.component('cone', {
transclude: true,
template: '<p>Component one</p><ng-transclude></ng-transclude>',
controller: function() {
console.log("component one loaded")
this.fone = function() {
console.log("component one function one")
}
}
})
.component('ctwo', {
template: '<p>Component two</p>',
controller: function() {
var vm = this;
console.log("component two loaded");
this.$onInit = function () {
console.log('calling fone from ctwo! ---->');
this.cone.fone();
};
},
require: {
cone: '^^cone'
}
})
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<div ng-app="app">
<cone>
<ctwo></ctwo>
</cone>
</div>
&#13;
答案 1 :(得分:0)
使用, require: '^cone',
angular.module("app", [])
.component('cone', {
template: '<p>Component one</p>',
controller: function() {
console.log("component one loaded")
this.fone = function() {
console.log("component one function one")
}
}
})
.component('ctwo', {
template: '<p>Component two</p>',
controller: function() {
console.log("component two loaded")
},
require: '^cone',
})
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<div ng-app="app">
<cone></cone>
<ctwo></ctwo>
</div>
&#13;