3

I need to implement component communication between two independent components. I have used require keyword but it throws an error

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

this is my code

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>
is am doing wrong? any idea ?
Ebin Manuval
  • 1,235
  • 14
  • 33
  • 1
    **ctwo** should be cone´s son `
    `
    – Naimad Apr 09 '18 at 08:11
  • https://stackoverflow.com/questions/38698953/angularjs-pass-data-from-controller-to-controller-without-factory-service-or/38699338#38699338 – gyc Apr 09 '18 at 08:27

2 Answers2

3

For component 2 to call component 1 functions you need to make component 2 a child of component 1. Either in the component 1 template or by transclusion:

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>
gyc
  • 4,300
  • 5
  • 32
  • 54
0

use, 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

Sravan
  • 18,467
  • 3
  • 30
  • 54