我有一个点击事件在表行,在这一行还有一个删除按钮与点击事件。当我点击删除按钮,点击事件上的行也被触发。
这是我的代码。
<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事件被触发?
如果你像我一样使用指令,这就是当你需要两种数据方式绑定时的工作方式,例如在任何模型或集合中更新属性后:
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>
如果你像我一样使用指令,这就是当你需要两种数据方式绑定时的工作方式,例如在任何模型或集合中更新属性后:
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>
我写了一个指令,让你限制点击有影响的区域。它可以用于像这样的特定场景,所以你可以直接说“点击不会从这个元素中出来”,而不是逐个处理点击。
你可以这样使用它:
<table>
<tr ng-repeat="user in users" ng-click="showUser(user)">
<td>{{user.firstname}}</td>
<td>{{user.lastname}}</td>
<td isolate-click>
<button class="btn" ng-click="deleteUser(user.id, $index);">
Delete
</button>
</td>
</tr>
</table>
请记住,这将阻止在最后一个单元格上的所有单击,而不仅仅是按钮。如果这不是你想要的,你可能想要像这样包装按钮:
<span isolate-click>
<button class="btn" ng-click="deleteUser(user.id, $index);">
Delete
</button>
</span>
下面是指令的代码:
angular.module('awesome', []).directive('isolateClick', function() {
return {
link: function(scope, elem) {
elem.on('click', function(e){
e.stopPropagation();
});
}
};
});