首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >组件通信angularjs 1.6

组件通信angularjs 1.6
EN

Stack Overflow用户
提问于 2018-04-09 08:02:39
回答 2查看 2.2K关注 0票数 3

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

错误:$compile:ctreq缺少必需的控制器 控制器‘锥形’,指令'ctwo‘所要求的,找不到!

这是我的密码

代码语言:javascript
复制
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'
    }
  })
代码语言:javascript
复制
<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>

我做错了吗?知道吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-04-09 08:47:59

要使组件2调用组件1函数,需要使组件2成为组件1的子组件。

代码语言:javascript
复制
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'
    }
  })
代码语言:javascript
复制
<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>

票数 3
EN

Stack Overflow用户

发布于 2018-04-09 08:14:17

使用,require: '^cone',

代码语言:javascript
复制
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',
      })
代码语言:javascript
复制
<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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49728134

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档