Skip to content Skip to sidebar Skip to footer

Binding Click Event To Child Element Inside Directive Of Angularjs

I have following directive. (function () { 'use strict'; angular.module('ap.App') .directive('clearCancelFinishButtonsHtml', function () { return {

Solution 1:

Thank you all for trying,

I got it working with the following 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");
                          });
                        }
                    })

                }
            }
        });
})();

Happy coding ;)

Solution 2:

why are you not using ng-click?

if you do this

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

and

<button type="button" class="custom-default clear" ng-click="clearClick()">CLEAR</button>

then it calls the function

Solution 3:

are you using jquery? because if not then the .find() method will only work with tag names (so class selectors won't work). So the problem here is that el.find('.clear') isn't getting your child element. Instead, use document.querySelector like this:

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

If you're not including jquery in your project then you only have access to jqlite. You can see what can and can't be done with it in the jqlite docs.

Post a Comment for "Binding Click Event To Child Element Inside Directive Of Angularjs"