Angularjs 使 HTML 元素可拖动且其中的 HTML 字段可选择或可修改的指令

Angularjs Directive to make HTML element draggable and HTML fields within it selectable or modifiable

我尝试了很多东西,但其中 none 有效。因此,发布相同的内容。

这是背景:

我有这个 HTML 元素,它将根据 ng-repeat 动态创建一个矩形框。在每个 Rectangular 框中都有各种 HTML 元素,例如 HTML select and input text 等,用户可以编辑这些字段。我想制作这个矩形框 draggable 以便用户可以移动它。

因此,我写了一个 angularjs directive 来完成它并且它工作正常但是如果我添加指令然后 select 字段和 rectangular 框中的所有字段都是不再可编辑,因为它将 draggable directive 应用于整个 rectangular。如果我删除此指令,那么它将正常工作。如何使 rectangulardraggable 以及其中的字段 selectable or editable?

HTML CODE:

<div ng-repeat="NewField in NewFieldValues">
    <div style="width:250px;height:120px;border:1px solid #000;" draggable draggable="true">
        <select ng-model="Dynamic.BusinessStep[NewField.ID]" ng-change="BusinessStepChange(NewField.ID,'BusinessStep')" class="form-control">
            <option class="dropdown-item" value="" selected> Choose Business Step</option>
            <option class="dropdown-item" ng-repeat="businessStep in businessSteps" value="{{ businessStep.value }}"> {{ businessStep.text }} </option>
        </select>
        <br/>
        <input type="text" ng-model="Dynamic.ObjectCount[NewField.ID]" ng-blur="BusinessStepChange(NewField.ID,'EventCount')" placeholder="number of objects" class="form-control"></input>
    </div>
    <br/>
</div>

Angularjs Directive:

app.directive('draggable', function($document) {
    return function(scope, element, attr) {
        var startX = 0, startY = 0, x = 0, y = 0;
        
        element.css({
            position: 'relative',
            border: '1px solid red',
            backgroundColor: 'lightgrey',
            cursor: 'pointer',
            display: 'block'
        });
        
        element.on('mousedown', function(event) {
            console.log("MOUSE DOWN");
            // Prevent default dragging of selected content
            event.preventDefault();
            startX = event.screenX - x;
            startY = event.screenY - y;
            $document.on('mousemove', mousemove);
            $document.on('mouseup', mouseup);
            return true;
        });

        function mousemove(event) {
            console.log("MOUSE MOVE");
            y = event.screenY - startY;
            x = event.screenX - startX;
            element.css({
              top   : y + 'px',
              left  : x + 'px'
            });
            return true;
        }

        function mouseup() {
            $document.off('mousemove', mousemove);
            $document.off('mouseup', mouseup);
            return true;
        }
    };
});

我尝试更改一些内容,但 none 中的内容有效。当我尝试将 draggable 添加到矩形框时,其中的字段默认获得 draggable directive,因此它们的 default 行为被 angularjs directive 覆盖。如果有人能在这里给我一些指导,我将不胜感激。

您遇到的问题是 Event-Bubbling。单击事件冒泡到触发拖动事件的容器矩形。

解决方案就是实现$event.stopPropagation();,这样做的目的是防止相关的$event冒泡并触发其他类似事件。