javascript - How work with $(target) inside directive? -


i build directive time selection 2 blocks. problem catch target event on blocks inside directive template. directive template:

<div class='time-picker-container'>     <div class='block1' ng-click='show()'>1</div>     <div class='block2' ng-show='selectvisible'>2</div> </div> 

js:

scope.selectvisible = false; scope.show = function() {     scope.selectvisible = scope.selectvisible ? false : true; } $rootscope.$on('documentclicked', function(inner, target) {     //try hide div.block2 if user make click outside block. }); 

basic idea: when user make click on document, outside div.block2, block disappear. when user click somewere inside div.block2 block stay visible.

on run function:

angular.element(document).on('click', function(e) {         $rootscope.$broadcast('documentclicked', angular.element(e.target));     }); 

in template, add $event argument ng-click handler function.

<div class='time-picker-container'>     <div class='block1' ng-click='show($event)'>1</div>     <div class='block2' ng-show='selectvisible'>2</div> </div> 

then in ng-click handler use stoppropagation() prevent outsideclickhandler getting called.

angular.module("myapp").controller("myvm", function($scope, $document) {     var vm = $scope;     vm.selectvisible = false;      vm.show = function(event) {        console.log("inside click");        event.stoppropagation();        vm.selectvisible = vm.selectvisible ? false : true;     }      function outsideclickhandler(e) {         console.log("outside click");         $scope.$apply("selectvisible = false");     }     $document.on("click", outsideclickhandler);      $scope.$on("destroy", function() {         $document.off("click", outsideclickhandler)     }) }) 

to prevent memory leaks, sure remove $document click handler when scope destroyed.

the demo on jsfiddle.


Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -