javascript - ngfocus - ng-disabled




AngularJS ng-click stopPropagation (4)

我在表格行上有一個點擊事件,在這一行中還有一個帶有點擊事件的刪除按鈕。 當我點擊刪除按鈕時,行上的單擊事件也被觸發。

這是我的代碼。

<tbody>
  <tr ng-repeat="user in users" class="repeat-animation" ng-click="showUser(user, $index)">
    <td>{{user.firstname}}</td>
    <td>{{user.lastname}}</td>
    <td>{{user.email}}</td>
    <td><button class="btn red btn-sm" ng-click="deleteUser(user.id, $index)">Delete</button></td>
  </tr>
</tbody>

我怎樣才能防止當我點擊表格單元格中的刪除按鈕時觸發showUser事件?


ngClick指令(以及所有其他事件指令)創建$event變量,它在相同的範圍內可用。 該變量是對JS event對象的引用,可用於調用stopPropagation()

<table>
  <tr ng-repeat="user in users" ng-click="showUser(user)">
    <td>{{user.firstname}}</td>
    <td>{{user.lastname}}</td>
    <td>
      <button class="btn" ng-click="deleteUser(user.id, $index); $event.stopPropagation();">
        Delete
      </button>
    </td>              
  </tr>
</table>

PLUNKER


如果您使用的是像我這樣的指令,那麼當您需要更新任何模型或集合中的屬性之後需要綁定兩個數據路徑時,它就是如何工作的:

angular.module('yourApp').directive('setSurveyInEditionMode', setSurveyInEditionMode)

function setSurveyInEditionMode() {
  return {
    restrict: 'A',
    link: function(scope, element, $attributes) {
      element.on('click', function(event){
        event.stopPropagation();
        // In order to work with stopPropagation and two data way binding
        // if you don't use scope.$apply in my case the model is not updated in the view when I click on the element that has my directive
        scope.$apply(function () {
          scope.mySurvey.inEditionMode = true;
          console.log('inside the directive')
        });
      });
    }
  }
}

現在,您可以輕鬆地在任何按鈕,鏈接,div等中使用它,如下所示:

<button set-survey-in-edition-mode >Edit survey</button>

除了Stewie的回答。 如果您的回調決定傳播是否應該停止,我發現將$event對像傳遞給回調會很有用:

<div ng-click="parentHandler($event)">
  <div ng-click="childHandler($event)">
  </div>
</div>

然後在回調本身中,您可以決定是否應該停止事件的傳播:

$scope.childHandler = function ($event) {
  if (wanna_stop_it()) {
    $event.stopPropagation();
  }
  ...
};

<ul class="col col-double clearfix">
 <li class="col__item" ng-repeat="location in searchLocations">
   <label>
    <input type="checkbox" ng-click="onLocationSelectionClicked($event)" checklist-model="selectedAuctions.locations" checklist-value="location.code" checklist-change="auctionSelectionChanged()" id="{{location.code}}"> {{location.displayName}}
   </label>



$scope.onLocationSelectionClicked = function($event) {
      if($scope.limitSelectionCountTo &&         $scope.selectedAuctions.locations.length == $scope.limitSelectionCountTo) {
         $event.currentTarget.checked=false;
      }
   };







angularjs-ng-click