How can I call a function in the parent component when clicking on the child component in Angular 1.5?

In my Angular 1.5 app, I have two components. The first one is the parent:

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);
        };
    }]
});

The second component is the child:

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

Below is how I implemented it in my index.html:

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

My question is: How can I trigger the function saySomething() from the parent component when clicking on the button in the child component? Currently, it's not working as expected. I've checked a similar question here but it didn't provide a solution to my issue. Thank you in advance for your assistance!

P.S. If there are any related questions or solutions available, please do share. Thank you!

Answer №1

To access the parent controller within a child component, you can use the require property to establish a connection and call 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>'
  });

Check out this demonstration

For more information, refer to the official documentation

Answer №2

the interesting part is that it exclusively functions for unidirectional bound values

   mod.component('myCmp', {
      template: '<h1>{{$ctrl.name}}</h1>',
      bindings: {
        name: '<'
      },
      controller:  {
      this.$onChanges = function (changesObj) {
        if (changesObj.name) {
         ...execute a specific function
        }
      };
    }
    });

Answer №3

Although I may be arriving late to the party, I believe there is a more efficient approach to handling this situation. Allow me to provide a brief example:

(function() {
    var app = angular.module('app');
    app.component('reportPrintButton', {
        template: [
            '<button class="btn btn-info" ng-click="$ctrl.onClick()">',
                '<span class="glyphicon glyphicon-print"></span> {{ $ctrl.name }}',
            '</button>'
        ].join(''),
        bindings: {
            name: '@',
            onClick: '&'
        },
        controller: reportPrintButton
    });

    reportPrintButton.$inject = [];

    function reportPrintButton() {
        var ctrl = this;
    }
})();

// When implementing on the view, utilize it as shown below. In the on-click attribute, specify the function
// you wish to execute from the parent component
<report-print-button name="Complete" on-click="printReport('Complete')">
</report-print-button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Execute an npm script using a gulp task

Is there a way to execute an npm script command within a gulp task? package.json "scripts": { "tsc": "tsc -w" } gulpfile.js gulp.task('compile:app', function(){ return gulp.src('src/**/*.ts') .pipe(/*execute npm run tsc*/ ...

The AngularJS change event is not being activated

I am a beginner with angular js and I have implemented a bootstrap calendar in my application. However, I am facing an issue where the change event is not being triggered when the month changes, no matter where I place it within the code. Here is the snip ...

Getting the value of a variable inside an onclick function

I am facing an issue with displaying the values of 2 variables inside an onclick event. I have tried the code below but it is not working. Can someone please help me solve this problem within the next 3 hours? var myCode = "12345"; var myCount = "5" $(&a ...

Accessing a precise div element in a webpage

Currently, I am utilizing Vue.js and Nuxt for my web development. One issue I am facing is related to anchors. Specifically, when I navigate to mysite.com/page1#section1, I want the page to scroll to section1. In my code, I have the following snippet: < ...

Getting your JQuery ready() statement right is crucial for the proper

I have come across all three variations below: $().ready(); $(document).ready(); $(document.body).ready(); All of them seem to work, but I'm wondering which one is the most appropriate or recommended to use when considering the usage of the ready() ...

How to Display an HTML Page or DOM Element on the Surface of a Cube using Three.js?

Currently, I am working on customizing the sample file canvas_geometry_cube.html that comes with the Three.js package. My goal is to replace each face of the cube with an HTML page or DOM element (preferably DOM element). While exploring, I came across P ...

jquery logic for iterating through all elements in a select menu encountering issues

In search of a solution to iterate through all options in a dropdown list using code, comparing each to a variable. When a match is found, I aim to set that particular value as the selected item in the dropdown and then exit the loop. Here's what I&ap ...

Dynamically import React Material UI Icons when needed

The concept here revolves around importing react material UI icons only when necessary, especially in situations where we may not know the icon name during compile time. (Ensuring that we have valid icon names) My method involved using a require statement ...

What is the best way to utilize $.post() to send a combination of a javascript object and form

I'm having trouble sending a JavaScript object along with form data using the shorthand method $.post(). I want to combine these two, but it's proving to be difficult. Additionally, I need to know how to retrieve the form data on my PHP page. An ...

There was a problem uploading the Feed document using amazon-sp-api: Invalid initialization vector encountered

I'm encountering an issue while attempting to upload a Feed document to Amazon using the createFeedDocument operation of the Selling Partner API. Following the API call, I received a response object that includes the feedDocumentId, url, and encryptio ...

Unable to execute $http in AngularJS Plunker

Having trouble running $http on the Plunker. Can you please review my code and assist me? var QuizApp = angular.module('QuizApp', []); QuizApp.controller('QuizController', ['$scope','$http',function($scope,$http) { ...

Having trouble understanding how to receive a response from an AJAX request

Here is the code that I am having an issue with: render() { var urlstr : string = 'http://localhost:8081/dashboard2/sustain-master/resources/data/search_energy_performance_by_region.php'; urlstr = urlstr + "?division=sdsdfdsf"; urlst ...

"Troubleshooting issue: Module fails to reload following JSON.parse error

For QA testing purposes, we have a test page that allows our QA team to replicate server behavior by passing JSON to a mock service. Everything functions correctly when valid JSON is used, but if invalid JSON is provided, an error is returned - which is ex ...

The dividers flicker in and out of view

I have a menu with 7 elements, where clicking on an element causes its content to appear by fading in. If another element is clicked, the current content fades out and the new content fades in. I've successfully implemented this concept for 3 of the 7 ...

Tips for enhancing the efficiency of your Node.js and Express.js code while steering clear of callback hell

One of the controllers in my application contains a method that is responsible for printing an array of URLs using the webshot package. Below is the code snippet in question: router.post('/capture', function (req, res, next) { //Check params ...

Toggle between tabs by dynamically selecting radio buttons

On my webpage, I have numerous tabs following the same structure as seen on the angular-ui page. Each section contains tabs for both Markup and Javascript. My goal is to implement two radio buttons at the top of the page that can switch all tabs to either ...

Unable to make a POST request to the GitHub v3 API

I'm attempting to generate a public gist using JavaScript without any authentication - all purely client-side. var gist = { "description": "test", "public": true, "files": { "test.txt": { "content": "contents" ...

How can you achieve the effect of "hovering over an image to automatically start playing a muted video within the image itself"?

[![enter image description here][1]][1]I am working with WordPress and Elementor, and I want to create a hover effect where an image triggers a muted video to play within the image area on mouseover. The video should stop playing when the mouse is not hove ...

Is there a way to click on an element using selenium even if it's not clickable? I'm unable to click on it

Is there a way to force a click on an element even if it says another element would be clicked? I really need to click on this select element: let input_provinces = await driver.findElement(By.id("select_provinces")).click(); Any help or advice ...

Unable to access the 'localStorage' property from 'Window': Permission denied

Check out my website www.abc.com Incorporating an iframe in www.abc.com using <iframe src="www.xyz.com"></iframe> An issue has arisen: Error message: "Failed to read the 'localStorage' property from 'Window': A ...