组件通信 angularjs 1.6

component communication angularjs 1.6

我需要实现两个独立组件之间的组件通信。 我使用了 require 关键字但它抛出错误

Error: $compile:ctreq Missing Required Controller
Controller 'cone', required by directive 'ctwo', can't be found!

这是我的代码

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'
    }
  })
<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>
我做错了吗?有什么想法吗?

使用,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',
      })
<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>

Here is Fiddle link

要使组件 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'
    }
  })
<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>