Connect an angular directive template to an event

In my Angular directive, the template structure is as follows:

<Button id="testBtn">Test me<button>

Within the directive controller, I have defined API functions for the directive. Now, I need to send an event to the parent module when the button is clicked. This will allow me to specify the action to be taken on the button click in the main application.

The following code snippet should be added to the base application controller:

$scope.myDirective = {
    btnClick:function(){
     // define the function here
    }
}

With the HTML template being structured like this:

<my-simpledirective='myDirective'></my-simpledirective>

I have managed to set up my configurations in the $scope.myDirective = {} section, but I am unsure how to define an event there.

For context, I am looking to achieve a similar functionality to how KendoUI handles events.

An alternative approach could be:

<my-simpledirective='myDirective' btn-clicked="myCustomClick"></my-simpledirective>

Then, in the base application controller:

$scope.myCustomClick = function(){
 // function to be called when click event is received
}

Answer №1

To establish bi-directional binding for the configuration object from the controller, you can set up scope like this:

app.directive('myCustomDirective', function() {
    return {
        scope: {
            config: '='
        },
        template: '<Button id="testBtn">{{config.label}}</button>',
        link: function(scope, element) {
            element.on('click', function(e) {
                scope.config.btnClick(e);
            });
        }
    };
});

Then, you can pass it in the template as shown below:

<my-custom-directive config='myConfig'></my-custom-directive>

Check out the live demonstration here: http://plnkr.co/edit/ue8EX9OR17iQxIi1ekco?p=preview

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

Ensure that the callback response in the $.ajax() function is treated as JSON dataType

My code snippet: <script> $('#email').on('blur', function(){ email = $(tihs).val(); $.ajax({ type: "POST", url: "ajax.php", data: { 'email': email, ...

Access arrays/objects within main object using JavaScript's Object.keys()方法

Perhaps the title is a bit confusing, but I couldn't come up with a better way to phrase it. I have a function that determines the value of each property within a contact object and returns 'No Data' if the value is null/empty/undefined. Ho ...

Effortless method to handle package.json configurations

Is there a better approach for seamlessly transitioning between using npm link and git, or another solution that caters well to both front end and back end developers? The dilemma I'm facing revolves around developing a website that utilizes multiple ...

How to retrieve a refined selection of items

In my scenario, there are two important objects - dropdownOptions and totalItem https://i.sstatic.net/VreXd.png The requirement is as follows: If 12 < totalItems < 24, then display "Show 12, Show 24" If 24 < totalItems < 36, only show "Show ...

What is the best way to set a background image that covers the entire screen while eliminating any borders on the sides using React and Material UI?

Working with Material-UI in React, I am attempting to set a background image behind a Paper component on the login page. Despite setting the image's backgroundSize to cover, there is still a white edge on the left and right sides of the screen. Below ...

What is the reason behind having all bindings resolved during each $digest cycle?

Upon placing a breakpoint on a bound function, I discovered that it is being triggered every cycle. This came as a surprise to me as the timer displaying a countdown on the page was updating other properties as well. The demonstration below showcases thre ...

Unlocking the Power of Large Numbers in Angular with Webpack

Error: [$injector:unpr] Unknown provider: BigNumberProvider Recently, I embarked on a new project using Webpack + Angular.JS and encountered an issue while trying to incorporate Bignumber.js. Here's a snippet of my Webpack configuration: resolv ...

Generate a new object from the contents of a div

Having the HTML structure below: <div id="main"> <div id="myDiv1"> <ul> <li>Abc</li> <li>Def</li> </ul> </div> <div id="myDiv2"> <ul> <li>Ghi</l ...

A Bluebird promise was generated within a NodeJS handler function, however it was not properly returned from the function

Below is the nodejs code for an express middleware function: Middleware.is_authenticated = function(req, res, next) { if(req.system_session == undefined || req.system_session.login_status == false) return res.status(401).send({errors: true, error: &ap ...

"Using Angular's NgFor directive to efficiently organize and collapse data within

I am currently working on displaying API data in a table using ngFor, and I am facing an issue with hiding/showing a specific row of details outside the ngFor loop. Since this line is not within the ngFor loop, I am unable to bind the data accordingly. Can ...

If a div element includes a specific text, then update that portion of the text without altering the value of any variables

Need help removing text without affecting variables Attempting to translate a specific line with JQuery Looking to change text only, leaving the content within the strong tag intact $('.content-box__row div:nth-child(3)').text('') ...

What is the method for pulling information from MySQL and presenting it on a website using Node.js?

Currently, my goal is to retrieve data from MySQL and showcase it on my HTML page. The code snippet in server.js looks like this: const path = require('path'); const express = require('express'); const bodyParser = require("body-pa ...

toggle visibility of a div using AngularJS

Struggling to hide/show a div using AngularJS, I have gone through multiple tutorials with no success. Finally opted for the code snippet mentioned in this link, but still facing issues. Can anyone assist me in identifying the problem? PS: Using angular ...

Troubleshooting the Height Problem in Material-UI's Menu

I am trying to make the menu height responsive by setting it equal to the window height using CSS. I want the menu height to increase as the page length increases due to added elements. I have attempted using "height:100%" and "height: 100vh" in the styles ...

Utilize JavaScript or jQuery to segment HTML elements

Looking for a front-end solution to a common practice. In the past, I've stored reusable HTML elements (such as <nav>, <header>, <footer>, etc.) in a functions.php file and used PHP functions to include them on multiple pages. This ...

Preserving the "height" declaration in jQuery post-Ajax request (adjusting height after dropdown selection loads product information, resetting heights of other page elements)

Looking for a way to set a height on product descriptions using jQuery? Check out the solution below: https://www.example.com/product-example Here is the code snippet that can help you achieve this feature: $(document).ready(function() { var $dscr = $ ...

Should I wait for my state to be updated with new information before triggering the render function?

Can someone assist me with restructuring the code below to ensure that the information in the data array is displayed on the initial page load? async componentDidMount() { const { id } = this.props.match.params const soccerApi = axio ...

What could be causing the data to be cut off to zero in my controller?

Currently in the process of migrating an application, and I've encountered some code that was already functioning properly. I have an Angular function that generates random AVL input to test my API. $scope.createAvl = function () { console.log($ ...

Dynamic HTML DOM element name changes

One thing I'm considering is the process of dynamically changing element names in the DOM with JavaScript or jQuery when adding or removing child elements. For instance, if I decide to delete the second text box from a form that originally has three t ...

Merge two distinct arrays of objects based on a shared field

I have two arrays of objects that I need to merge, with the expected output as: [ { "scenario": [ { "errorname": "Error 01", "status": 5, "desc_1" : "test", "desc_2" : "testing" }, ...