【问题标题】:component communication angularjs 1.6组件通信 angularjs 1.6
【发布时间】:2018-09-18 13:38:11
【问题描述】:

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

错误:$compile:ctreq 缺少必需的控制器
找不到指令“ctwo”所需的控制器“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: '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>
做错了吗?任何想法 ?

【问题讨论】:

标签: angularjs angular-components angular1.6


【解决方案1】:

要让组件 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>

【讨论】:

    【解决方案2】:

    使用,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

    【讨论】:

    • 我怎样才能从ctwo调用cone函数fone
    • @EbinManuval 你不能,ctwo 需要是锥体的孩子
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    相关资源
    最近更新 更多