组件通信angularjs 1.6

时间:2018-04-09 08:02:39

标签: angularjs angular-components angular1.6

我需要在两个独立组件之间实现组件通信。 我使用了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'
    }
  })
我做错了吗?任何想法?

2 个答案:

答案 0 :(得分:3)

对于组件2调用组件1函数,您需要使组件2成为组件1的子组件。在组件1模板中或通过包含:

&#13;
&#13;
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;
&#13;
&#13;

答案 1 :(得分:0)

使用, require: '^cone',

&#13;
&#13;
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;
&#13;
&#13;

Here is Fiddle link