user17045467
user17045467

Reputation:

ng-click for an entire DIV in AngularJS

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?

Upvotes: 0

Views: 300

Answers (1)

Nitheesh
Nitheesh

Reputation: 19986

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>

Upvotes: 1

Related Questions