Angular 1.5, Calling a function in a component from Parent controller

前端 未结 2 612
难免孤独
难免孤独 2021-01-31 17:36

Angular 1.5 components easily allow creating a call back to the parent from the component. Is there a way i can call a function in a component from a function in parent\'s contr

2条回答
  •  广开言路
    2021-01-31 18:20

    I needed something like this previously so I thought I would share how I solved this problem.

    Similar to the OP, I needed to freely trigger methods in child components from a parent component. I wanted to be able to trigger this method in the parent freely/separately without the use of the $onChanges lifecycle hook.

    Instead I created a notification-registration mechanism to allow a child component to 'register' a method with the parent when it is loaded. This method can then be freely triggered by the parent outside of the $onChanges cycle.

    I created a codepen to demonstrate this. It can be easily extended to handle different types of notifications from the parent that aren't related to the data changes.

    Index.html

    Script.js

    angular.module('tester', []);
    
    angular.module('tester').component('parent', {
      controller: parentController,
      template: `
        
    ` }); function parentController() { let childComponentEventHandler = null; this.$onInit = function() { this.value = 0; }; this.childComponentNotificationRegistration = function(handler) { childComponentEventHandler = handler; console.log('Child component registered.'); }; this.notifyChild = function() { if (childComponentEventHandler) { childComponentEventHandler(this.value++); } }; } angular.module('tester').component('child', { bindings: { parentToChildNotificationRegistration: '&', }, controller: childController, template: `

    Child Component

    ` }); function childController() { this.$onInit = function() { this.parentToChildNotificationRegistration({ handler: this.processParentNotification }); }; this.processParentNotification= function(parentValue) { console.log('Parent triggered child notification handler!!!'); console.log('Value passed to handler:', parentValue); }; };

    }

    Also for something similar to @adam0101's #3 answer see codepen.

提交回复
热议问题