![](/img/trans.png)
[英]AngularJS: How to dynamically add a function to a appended html element within a directive
[英]Angularjs Directive to make HTML element draggable and HTML fields within it selectable or modifiable
我嘗試了很多東西,但沒有一個有效。 因此,發布相同的內容。
這是背景:
我有這個HTML
元素,它將基於ng-repeat
動態創建一個矩形框。 在每個Rectangular
框中都有各種 HTML 元素,例如HTML select and input text
等,這些字段可以由用戶編輯。 我想讓這個矩形框draggable
,以便用戶可以移動它。
因此,我編寫了一個angularjs directive
來完成它並且它工作正常但是如果我添加指令,那么select
字段和rectangular
框內的所有字段都不再可編輯,因為它將draggable directive
應用於整個rectangular
。 如果我刪除此指令,那么它會正常工作。 如何使rectangular
框draggable
,以及其中的字段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;
}
};
});
我試圖改變一些東西,但它們都不起作用。 當我嘗試將draggable
對象添加到矩形框中時,默認情況下其中的字段會獲取draggable directive
,因此它們的default
行為被angularjs directive
覆蓋。 如果有人可以在這里為我提供一些指導,我將不勝感激。
解決方案是簡單地實現$event.stopPropagation();
,這樣做是為了防止相關的$event
冒泡並觸發其他類似事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.