Mik*_*lan 6 twitter-bootstrap angularjs angular-ui-router
我对该uiSref指令有一个有趣的问题,我无法在网络上的任何地方找到解决方案(无论如何都是优雅的解决方案).基本上,我要求客户端能够单击资源表中的行并转到该资源的编辑视图.通常情况下,该uiSref指令运行得很漂亮,但问题在于我<td>在表的最后一个中有一个Bootstrap下拉列表,其中有一堆快速操作.HTML看起来像这样:
<table class="table table-bordedered table-hover">
<thead>
<tr>
<td>Name</td>
<td>Actions</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="resource in resources" ui-sref="edit({id: resource.id})">
<td ng-bind="resource.name"></td>
<td class="actions-column">
<div class="btn btn-xs btn-default" data-toggle="dropdown">
<i class="fa fa-cog"></i>
</div>
<ul class="dropdown-menu pull-right">
<li>
<a href="javascript:void(0)" ng-click="doSomethingCrazy(resource)">SOMETHING CRAZY</a>
</li>
</ul>
</td>
</tr>
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
问题是,当我单击actions列中的按钮时,将uiSref覆盖下拉列表的默认操作并将我带到编辑页面.现在你可能会问自己"这很容易,为什么你不能阻止事件的传播!?"......不起作用.当我将其添加到actions列时:
<td class="actions-column" ng-click="$event.stopPropagation()">
Run Code Online (Sandbox Code Playgroud)
它会杀死下拉菜单的功能,但不显示任何内容.现在我有一个解决方法,我ngClick在<tr>元素上定义一个元素,然后根据点击的元素解密状态应该去的地方,如下所示:
<tr ng-repeat="resource in resources" ng-click="goToEdit(resource, $event)">
Run Code Online (Sandbox Code Playgroud)
JS看起来像这样:
scope.goToEdit = function(resource, event) {
// if the event.target has parent '.actions-column' or is that column, do nothing else
// invoke $state.go('edit', {id: resource.id})
}
Run Code Online (Sandbox Code Playgroud)
我讨厌它,我有很多像这样的列表视图.我正在寻找的是一个优雅和便携的解决方案,希望通过UI路由器本身工作$event.stopPropagation()(虽然我已经通过UI路由器源,但似乎找不到一个可行的替代方案).基本上我想吃蛋糕也吃.无论如何,看到SO社区可以提出什么,或者我要求的东西目前是不可能的,这将是有趣的.谢谢!
我知道了!在查看UI路由器源代码时,如果在target所uiSref驻留的元素上填充属性,则会忽略click事件.它可能不是世界上最美丽的东西,但它肯定比我以前做的更容易.
注意:这仅适用于您使用整个jQuery库,而不是jQLite
所以我写了这个指令:
app.directive('uiSrefIgnore', function() {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
elem.on('click', function(e) {
// Find the ui sref parent
var uiSref = elem.parents('[ui-sref]').first();
// Set the target attribute so that the click event is ignored
uiSref.attr({
target: 'true'
});
// Function to remove the target attribute pushed to the bottom
// of the event loop. This allows for a digest cycle to be run
// and the uiSref element will be evaluated while the attribute
// is populated
setTimeout(function() {
uiSref.attr({
target: null
});
}, 0);
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
这样,每当我想忽略uiSref指令的javascript事件时,我只需将其添加到html中:
<tr ui-sref="edit">
<!-- any other elements -->
<td ui-sref-ignore>The element I care about</td>
</tr>
Run Code Online (Sandbox Code Playgroud)
繁荣!让我知道你们对这个问题的看法.
| 归档时间: |
|
| 查看次数: |
3170 次 |
| 最近记录: |