0

Whenever any element inside my DIV is clicked I want to execute a function in Angular controller.

How to do this?

Basically I am looking to place a ng-click on DIV element and expect the ng-click event be called when any/all elements nested inside the div are clicked.

How to achieve this requirement?

3
  • Place the ng-click on this div? Have you tried it? Commented Oct 4, 2021 at 15:57
  • Yes. I did. It doesn't seems to fire/called. Commented Oct 4, 2021 at 16:05
  • 1
    A container with ng-click and a button inside that container with ng-click can demonstrate it. When you click the button inside the container, the ng-ckick of button will be triggered first there after the click of container will also be triggered Commented Oct 4, 2021 at 16:05

1 Answer 1

1

Here both the container and the button has click events. When you click the button, the click event of its parent will also be triggered. This is called Event Bubbling in JavaScript

var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
    $scope.clicked = function() {
        console.log("Clicked Me");
    };
    $scope.secondclick = function() {
        console.log("Button Clicked")
    }
});
.container {
    width: 100%;
    height: 300px;
    background: cyan;
    cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
    <div class="container" ng-click="clicked()">
        <button ng-click="secondclick()">Click Me</button>
    </div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.