我有一个组件,它是一个用于打开和关闭下拉元素的按钮,以及当存在 ng-model 值时用户可以清除下拉列表中所选项目的选项,如下所示:
<button class="btn btn-default form-control" type="button" ng-click="ctrl.toggleDropdown($event)" ng-keydown="ctrl.onKeyboardPressed($event)" ng-mouseenter="icon=true" ng-mouseleave="icon=false">
<span ng-if="ctrl.ngModel !== null" >
{{ctrl.ngModelValue ? ctrl.ngModelValue : ctrl.placeholder}}
<i class="removeSelectionIcon" ng-class="{'fa fa-close' : icon}" ng-mousedown="ctrl.clearSelection($event)"></i>
</span>
</button>
为了简单起见,当用户通过 ng-mousedown 单击“fa fa-close”图标时,我需要触发以下函数:
function clearSelection($event) {
console.log("hey there");
this.ngModel = null;
this.ngModelValue = "";
$event.preventDefault();
$event.stopPropagation();
}
在 Chrome 中一切都很好,但我什至无法在 IE 和 Firefox 中获取 console.log。当我单击该图标时,下拉菜单会打开和关闭,就像我单击按钮本身一样。我注意到,如果我快速双击该图标,我可以清除所选行,但是有人知道我需要做什么才能在我单击“fa fa-close”图标时触发 mousedown 事件吗?
非常感谢您的帮助!
最佳答案
这似乎是由于嵌套在 <button>
中造成的元素。使用另一个元素作为父“按钮”,例如 <div>
,生成您在 Firefox 和 Internet Explorer 中查找的结果。
这是一个 plunker 演示了两者。 https://plnkr.co/edit/wJ6OB7?p=preview
一般来说,我认为真正的问题是,虽然您可以将 HTML 元素嵌套在按钮内(而不是 <input type="button">
内),但以这种方式嵌套充当按钮的元素可能不是一个好主意。
关于javascript - 在 IE 和 Firefox 中使用嵌套在按钮内的 ng-mousedown 调用 Angular Controller 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36437845/