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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With