Search code examples
javascriptangularjsecmascript-6angularjs-controllerangularjs-components

How to use a function from Component inside the page controller in AngularJS?


I want to use a function from a component inside my page.controller First, I don't know if it is possible? and Second, if it is possible, how should I do that?

Here I have have function inside the component.controller called checkStatus, I want to execute it, therefore my ng-disabled turns false and I can click on SAVE button.

testComponent.component.js:

export default {
  template: temp,
  controller: myComponentController,
  controllerAs: 'vm',
  bindings: {
    popupMsg : '&'
  }
};

function myComponentController() {
  'ngInject';

  this.popupMsg = function() {
    alert("It is working!");
    this.checkStatus();
  };

  this.checkStatus = function() {
    this.mustPass = true;
  };

}

myPage.controller.js:

export class MyPageController {

  constructor() {
    'ngInject'
    ...
  }

  save() {
    ...
  }
}

myPage.html:

<form>
<test-component mandatory="vm.popupMsg()"> </test-component>

<div>
  <button type="submit" ng-click="vm.save()" ng-disabled="!vm.mustPass"> Save </button>
</div>
</form>

Plunker for testing


Solution

  • You need to have output bindings on your testComponent.

    testComponent.component.js

    bindings: {
      statusChange: '&'
    
    }
    
    function myComponentController() {
    
         this.checkStatus = function() {
            this.mustPass = true;
            this.statusChange({$event: this.mustPass});
        };
    

    mypage.html

    <test-component mandatory="vm.popupMsg()" status-change="vm.onStatusChange($event)"> </test-component>