简体   繁体   English

ng-repeat中的AngularJS指令

[英]AngularJS directive inside ng-repeat

I'm creating a drag & drop directive in AngularJS. 我正在AngularJS中创建拖放指令。 I'm having problems with my directive being inside an ng-repeat . 我的directive位于ng-repeat内时遇到问题。

The problem is that when I drag my element onto a droppable div, it always takes the last element from the list. 问题是,当我将元素拖动到可放置div时,它总是从列表中获取最后一个元素。 If I drag the first one in the list it still takes the last one being dropped. 如果我将列表中的第一个拖动,它将仍然删除最后一个。 This is my HTML: 这是我的HTML:

<li ng-repeat="data in source">
   <div draggable="#divDrop" drop-model="otherList" push-object="data">
      {{data.name}} {{data.price}}
   </div>
</li>

<div id="divDrop" class="alert alert-info">Drag your data into this box</div>

Finally I have a simple directive as follows: 最后,我有一个简单的指令,如下所示:

app.directive('draggable', function($timeout) {
            return {
                scope: {
                    dropModel: '=',
                    pushObject: '='
                },
                link: function (scope, element, attrs) {
                    $timeout(function () {
                        var draggableEl = attrs.draggable;

                        $(draggableEl).droppable({
                            drop: function (event, ui) {
                                scope.dropModel.push(scope.pushObject);
                                scope.$apply();
                            }
                        });

                        $(element).draggable({
                            revert: true,
                            revertDuration: 0
                        });
                    });
                }
            };
        });

Just to be clear, scope.pushObject is always the last item in the ng-repeat and not the item being dragged. 需要明确的是, scope.pushObject始终是ng-repeat的最后一个项目,而不是被拖动的项目。

You could access the scope of each item being dragged like this: 您可以像这样访问要拖动的每个项目的范围:

drop: function (event, ui) {
    var data = $(ui.draggable).scope().data;

    scope.dropModel.push(data);
    scope.$apply();
}

Then you wouldn't need pushObject on the directive scope. 这样,您就不需要指令范围内的pushObject

http://plnkr.co/eo7zCRu0JA1mLdVekGiK http://plnkr.co/eo7zCRu0JA1mLdVekGiK

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM