所以我正在尝试使用 mootools 创建拖放购物车,如下所示:demo .我可以让代码工作得很好,但是当我尝试编辑他们的 html 使其看起来像 html beloe 时,它停止工作。 css 仍然像人们预期的那样适用,并且 ng-repeat 之外的 div 工作正常。但是,我很确定 mootools javascript 中的 .addEvent 无法在 ng-repeat 中“找到”.item,因此我无法在 ng-repeat 中获取任何 .items。
有什么想法吗?
更新: 好的,看来问题涉及javascript中的domready事件。触发时 angularjs 尚未加载。我尝试了加载事件,但这也会在 angularjs 加载之前触发。对于事件还有其他想法吗?我现在正在使用 mousedown,但这意味着您必须先单击其中一个图像才能开始拖动它们,这不是最佳选择。此外,mousedown 事件似乎有时会导致购物车中出现奇怪的重复项,因此我需要找到更好的方法。
<div id="items">
<div class="item">
<p>test</p>
</div>
<div ng-repeat="post in posts">
<div class="item">
<img class="picImage" src="/static/imgs/{{post.picture}}" alt="Smiley face" height="128" width="128">
<p>Shirt 1</p>
</div>
</div>
</div>
最佳答案
取决于您如何附加可拖动对象。问题是,在 ng-repeat 通过 $scope.$apply
等应用程序的这一部分的生命周期呈现之前,这些元素将不存在。
// this code is wrong.
$$('.item').addEvent('mousedown', function(event){
event.stop();
...
});
此外,如果集合发生变化,mootools 将不知道添加新的点击处理程序。
您不想等待 ng 更改内容并重新应用 mootools 事件,这不是一个好主意。
您可以使用:https://docs.angularjs.org/api/ng/directive/ngMousedown将事件绑定(bind)到集合元素,添加一个 $scope.onMouseDown
并将逻辑移到那里,让 Angular 在内部处理它:
<div ng-repeat="post in posts">
<div class="item" ng-mousedown="onMouseDown($event, post, $index)">
<img class="picImage" src="/static/imgs/{{post.picture}}" alt="Smiley face" height="128" width="128">
<p>Shirt 1</p>
</div>
</div>
用类似的东西
$scope.onMouseDown = function($event, post, $index){
// clone and do stuff
// if you want to disable stuff, modify `post` etc, potentially can do $scope.$digest / $apply ...
};
...或者您可以使用事件委托(delegate)并像这样绑定(bind):
$('items').addEvent('mousedown:relay(.items)', function(event){
// ... do normal logic but no access to ng model here. can get dirty
});
事件委托(delegate)(如上通过中继)将工作正常,只要 Angular 不决定重新渲染 div#items
是因为渲染了你的应用程序的那部分。如果是这样,它将破坏保存的事件。这也意味着您需要能够首先看到该元素才能通过 mootools 绑定(bind)到它。
为了安全起见,您可能希望将事件绑定(bind)到您的 ng-app div 并委托(delegate)给这个:
document.getElement('[ng-app]').addEvent('mousedown:relay(#items div.items)', fn);
关于javascript - Mootools .addEvent 无法进入 ng-repeat?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25943258/