I am trying to detect a document click when user clicks anywhere in the page . I also want to prevent clicking a div to trigger the document clicks.
I have something like
//Directive for page click
angular.module('myApp').directive('documentClick', ['$rootScope',
function($rootScope) {
return function(scope, element, attrs) {
element.bind('click', function(e){
$rootScope.$broadcast('pageClick');
})
}
}]);
controller JS
//within a controller
$scope.toggleDiv = function() {
$scope.openDiv = !$scope.OpenDiv;
}
$scope.$on('pageClick', function($event) {
$scope.openDiv = false;
})
html
<body document-click>
<div ng-controller = 'ctrl'>
<div id='testDiv'>
<div id='childDiv' ng-click="toggleDiv()">
toggle div here
</div>
</div>
</div>
</body>
I don't want to trigger $scoep.openDiv = false
when I click ' childDiv
'. I only want to trigger $scope.openDiv = false
when I click anywhere in the page.
Is there an angular way to do this?
Thanks!
You could pass down the event e
and check the target.id
:
$rootScope.$broadcast('pageClick', e);
$scope.$on('pageClick', function($event, e) {
if(e.target.id !== 'childDiv')
$scope.openDiv = false;
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.