按钮和主体 onclick 事件同时触发

angular.element('body').on('click', function () {

        //  $('.dropdown-menu').hide();

    console.log("clicked outside");

        });

$scope.showDropdown = function (e) {

      $scope.filterClick = !$scope.filterClick;

      e.stopPropagation();

}

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.4/angular.min.js"></script>

<button id="btn-append-to-body" type="button" class="btn btn-primary" 

        ng-click="showDropdown()">

    <img src="assets/images/filterIcon.png">

    &nbsp&nbspFilter <span class="caret"></span>

</button>


  <li class="nav-item dropdown" ng-hide="filterClick">

      <div class="dropdown-menu">

        <div class="dropdown-item" ng-repeat="item in items">

          <div class="filter-class">

          </div>

        </div>

      </div>

  </li>

我有按钮点击和正文点击功能。但是,如果我在单击正文时在控制台中打印任何值,则它工作正常。但同样的功能也适用于按钮点击。


我的需要是,


1)如果我单击按钮,主体 onclick 不应触发。只有按钮 onclick 应该工作。


2)单击按钮,过滤器下拉菜单正在打开。当我再次单击同一个按钮时,它正在关闭。(切换)


3)但是当我点击外面的任何地方时,我想隐藏那个下拉菜单。但它不起作用。


我如何使用 angularjs 做到这一点?


动漫人物
浏览 226回答 2
2回答

呼啦一阵风

在子按钮元素回调函数中使用 event.stopPropagation() 。angular.element('#btn-append-to-body').on('click', function () {&nbsp; &nbsp; event.stopPropagation();});

慕的地10843

在子 ie 按钮中通过 ng-click 传递 $event ,然后在 child 方法中的事件上传递 stopPropagation() 。StopPropagation 停止事件冒泡。HTML&nbsp; &nbsp; <div ng-click='parentClick()'>&nbsp; &nbsp; &nbsp; &nbsp; <button ng-click="childClick($event)">Click Me</button>&nbsp; &nbsp; </div>JS&nbsp; &nbsp; var myApp = angular.module('myApp', []);&nbsp; &nbsp; function MyCtrl($scope) {&nbsp; &nbsp; &nbsp; &nbsp; $scope.parentClick = function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert('Parent clicked');&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; $scope.childClick = function(event) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; event.stopPropagation();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert('Child clicked');&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript