简体   繁体   中英

How to prevent a ng-click event on a div in a sub controller from triggering an ng-click in the root?

http://plnkr.co/edit/gB7MtVOOHH0FBJYa6P8t?p=preview

在此处输入图片说明

I have a parent child controller example above, in the child when a button is clicked I displays the div showPop and then will $emit an event upwards to the $rootScope .

Now in the parent / $rootScope I "hear" that event then activate another function.

That function in the $rootScope triggers the bodyClick click function to be active, so once a click is registered in the body/parent/rootScope the div showPop is now hidden.

The problem is that while I want clicks on the body to close that div out, I do NOT want clicks on the actual div itself to trigger it to close?

How could I accomplish this / work around the $rootScope ng-click event?

.controller('mainController', ['$scope', '$rootScope',
                              function($scope,$rootScope) {

  var unbind = $rootScope.$on('popoverOpen');

  $scope.$on('popoverOpen', function(events, data) {
    console.log('popoverOpen is heard!')
    $scope.bodyClick = function() {
        console.log('bodyClick sent down from main');
        $scope.theAction = 'bodyClick sent down from main';
        $rootScope.$broadcast('bodyClick');
    };

    $scope.$on('$destroy', unbind);
  });
}])

.controller('subController', ['$scope', '$rootScope',
                             function($scope, $rootScope) {

  $scope.callPop = function($event) {
    $rootScope.theAction = 'popoverOpen emitted up from sub';
    $event.stopPropagation();
    $scope.showPop = true;
    $scope.$emit('popoverOpen');
  };

  $scope.$on('bodyClick', function() {

    console.log('bodyClick received in sub!');
    $rootScope.theAction = 'bodyClick received in sub!';
    $scope.showPop = false;
    $scope.$emit('destroy');
  });
}]);

Markup:

<body ng-app="app" ng-controller="mainController" ng-click="bodyClick()">

<h1>mainController</h1>

<div class="sidebar" ng-controller="subController">
  <h2>subController</h2>
  <button ng-click="callPop($event)">Click Me</button>

  <div ng-show="showPop" class="pop-box">This is showPop, clicking in here should not close it, clicking outside should!</div>
</div>

<section class="the-section">
  {{theAction}}
</section>

</body>

You could try something with an overlay. A click on the overlay close the pop and also prevent the click to go further.

Glad this suggestion helped you.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM