Attaching a click event to a nested element within an AngularJS directive

I am currently working with the following directive.

(function () {
    'use strict';
    angular.module('ap.App')
        .directive('clearCancelFinishButtonsHtml', function () {
            return {
                scope: {
                    clearFunction: '='
                },
                replace: true,
                templateUrl: 'directives/clearCancelFinishButtons.html',
                link: function (scope, el, attrs) {
                    var clear= angular.element(el.find('button.clear'));
                    console.log(el.find('.clear'));
                    clear.bind("click", function () {
                        alert("here");
                    });
                }
            }
        });
})();

In my code, the above directive is associated with the following HTML structure:

<div class="row pull-right">
    <div class="col-lg-12 col-md-12 col-sm-12">
        <button type="button" class="custom-default clear">CLEAR</button>
        <button type="button" class="custom-danger">CANCEL</button>
        <button type="button" class="custom-info" ng-click="ap.save()">FINISH</button>
    </div>
</div>

The main goal I have is to target the button with the clear class within the directive and trigger a click event on it. However, despite being able to implement the click event for the element itself, I'm facing difficulties in binding it to the child element. Any assistance or suggestions on this matter would be highly appreciated.

PS. The way I am using the directive is

<clear-cancel-finish-buttons-html id="{{$id}}" clear-function="'resetConfigurationPageInputs'">
</clear-cancel-finish-buttons-html>

UPDATE----------

My ultimate objective is to dynamically add and remove functions directly from the directive declaration itself.

Answer №1

Thank you everyone for your efforts,

I managed to make it function with this piece of code.

(function () {
    'use strict';
    angular.module('ap.App')
        .directive('clearCancelFinishButtonsHtml', function () {
            return {
                scope: {
                    clearFunction: '='
                },
                replace: true,
                templateUrl: 'directives/clearCancelFinishButtons.html',
                link: function (scope, el, attrs) {
                    var buttons=el.find('button');
                    angular.forEach(buttons, function(button){
                        var buttonEl=angular.element(button);
                        if(buttonEl.hasClass("clear")){
                            buttonEl.bind("click", function () {
                              alert("here");
                          });
                        }
                    })

                }
            }
        });
})();

Wishing you productive coding sessions ;)

Answer №2

Have you considered using ng-click for this task?

If you implement the following code snippet:

link: function (scope, el, attrs) {
  scope.clickHandler = function () { alert('click') };
}

and

<button type="button" class="custom-default click-button" ng-click="clickHandler()">CLICK ME</button>

you will see that the function gets called successfully.

Answer №3

Do you happen to be utilizing jQuery? If not, keep in mind that the .find() method will solely function with tag names, rendering class selectors ineffective. The issue at hand is that el.find('.clear') isn't targeting your child element. Instead, consider using document.querySelector as shown below:

var clear= angular.element(el[0].querySelector('button.clear'));

If jQuery is not part of your project, then only jqlite is available to you. For more information on what can and cannot be achieved with jqlite, refer to the jqlite documentation.

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

Examining Resolver Functionality within NestJS

Today I am diving into the world of writing tests for NestJs resolvers. I have already written tests for my services, but now it's time to tackle testing resolvers. However, I realized that there is a lack of documentation on testing resolvers in the ...

Ways to adjust the width of the Dialog box in Jquery UI to 60% of the window size

Currently, I am utilizing Jquery UI for a pop-up feature that displays a table populated through an Ajax call. The script implementation is as follows: <script> $(function() { $( "#dialog" ).dialog({ autoOpen: false, show: { ...

Ways to attribute a numeric worth to a choice in a JavaScript form

I am in the process of creating a form that allows users to customize and order pizza while showing them the invoice as they make their selections. Currently, I have successfully implemented the display of user-selected options, but I am struggling with a ...

Delete the tag that comes before

Is there a specific tag like: <p id="name" onclick="javascript:var ele=context(this);">sumtext here</p><br> <p id="name" onclick="javascript:var ele=context(this);">newtext here</p><br> <script ...

Show singular array element upon click

I need help with a specific task. When a button is clicked, I want to display a random item from an array. Each array item should only be displayed once. Currently, my code is set up as follows: When the button is clicked, a random array item is displ ...

Capturing member function details using JSDoc

Here's the code snippet I'm working with: /** This class blah blah... @constructor **/ my.namespace.ClassA = function(type) { /** This function performs an action **/ this.doSomething = function(param){ } } The class will be inc ...

Issues with Jquery/AJAX function not responding to onChange Event

I am currently working on a project where I need to populate a dropdown menu based on the value selected from another dropdown. However, I am encountering an issue with the function that I am trying to call in the onChange event of the select tag. This is ...

Codemirror - Advanced Auto-Suggest Feature with Separator

Can a separator be easily added in the hints/autocomplete addon? This separator would help transform the suggestion box to look like: f1 f2 f3 --- var1 var2 ...

"Retrieve a list of all routes that have been registered in Node.js

I am trying to retrieve a list of all registered routes in my project. Here is the code I have used for this purpose: const app = require("express"); let routers = app._router.stack .filter((r) => r.route) .map((r) => { return { ...

Regular Expression: locate the occurrence of "//" followed by any character other than a space

I am looking to add a space by replacing the target with the code "// ". That's all you need to know from the title. My attempts so far have looked like this: \/\/\b(?! ) However, this approach does not catch strings like "//$..." ...

Create a navigation link using ui.sref that targets a sub-state within another sub-state

What I am trying to accomplish: Within the template of the main state (/model), I have links leading to a child state phase (/phase). But, my goal is to also have the ability to directly link from the main state to a specific child state within a particul ...

Tips for keeping the most recently opened accordion in a group by using the is-open attribute to call a function

I have a dynamically populated accordion that updates every 15 seconds. I need to keep track of the last opened accordion group as the dataList can be very large and parsing it for each update is not feasible. Below is the code snippet from my HTML file: ...

Store the active tab in AngularJS with Bootstrap to easily remember and display

After creating a basic AngularJS application with the Bootstrap directive, I noticed that some of my pages have tabs. The issue arises when I am on a tab other than the first one and click a link to navigate to another view. Upon returning (using either th ...

Contrasting "npm run dev" with "npm start"

I have just started learning about Node and AngularJS. Could someone explain the distinction between npm run dev and npm start commands in the node terminal? ...

Error: The JavaScript function you are trying to use is not defined

Hi there, I'm new to javascript and angularjs. I've created a function in my controller to open a website when clicking on a button. However, I'm encountering an error message saying ReferenceError: openWebsite is not defined when trying to ...

Is it a good idea to relocate the document.ready function into its own JavaScript function?

Can the following code be placed inside a separate JavaScript function within a jQuery document.ready, allowing it to be called like any other JavaScript function? <script type="text/javascript"> $(document).ready(function() { $('div#infoi ...

Is there a way to dynamically change the height in jQuery/JavaScript?

I am encountering an issue with my embed code where the height changes randomly after a few seconds, depending on certain parameters. Here is an example of the code I am using: $( <embed></embed>) .attr("src", "http://www.bbs.com") ...

Check for duplicate in AngularJS and replace with larger duplicate

I have this piece of code where I am currently checking for duplicates using the isDuplicate boolean. However, I now want to enhance my code by comparing another property called colorId and then setting the isBigger property for the larger one :) Do you ha ...

encountered net::ERR_EMPTY_RESPONSE while attempting to locate a CSS file within an AngularJS directive

Every time my webpage attempts to access the css file from a directive, I encounter a net::ERR_EMPTY_RESPONSE. I have implemented door3's on-demand css feature, which allows for lazy loading of css files only when necessary. This feature works flawle ...

Input field modified upon focus

I am currently using selectize js in my section to create a select box. My goal is to make the input editable after selecting an option when it is focused on. Check out the live demo: live demo HTML <label>Single selection <select id=" ...