Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 1.5. | invoke a function from parent component clicking on child component?

In my app with angular 1.5 there are two components. A parent one:

angular.
module('myApp').
component('myContainer', {
    bindings: {
        saySomething: '&'
    },
    controller: ['$scope', function MyController($scope) {
        var containerCtrl = this;
        containerCtrl.saySomething = function saySomething() {
            containerCtrl.sentence = "Hello, world";
            console.log(containerCtrl.sentence);
        };
    }]
});

And a child one:

angular.
module('myApp').
component('myButton', {
    bindings: {
        onClick: '&'
    },
    template:
    '<div>' +
        '<a class="button" href="#">Say Something</a>' +
    '</div>'
}); 

And here is my index.html:

<my-container>
    <my-button ng-click="$ctrl.saySomething()"></my-button>
</my-container>

The question is: how to invoke the function saySomething() from the parent component by clicking on the button in the child component? Now it doesn't work. I've seen a similar question here but this didn't solve my problem. Thanks in advance for the help!

P.S. If there are any similar questions, please, let me know. Tnanks!

like image 650
Ms.Smith Avatar asked May 29 '26 19:05

Ms.Smith


1 Answers

You can require parent controller in child component and then invoke its methods.

angular.module('demoApp', [])
  .component('myContainer', {
    ...
  })
  .component('myButton', {
    require: {
      parentCtrl: '^myContainer'
    },
    template: '<div>' +
      '<a class="button" href="#" ng-click="$ctrl.parentCtrl.saySomething()">Say Something</a>' +
      '</div>'
  });

Here's a demo

And link to documentation

like image 58
Aleksey L. Avatar answered Jun 01 '26 08:06

Aleksey L.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!