[英]AngularJS : Directive updating parent scope inside of ng-repeat
我在圖像的ng-repeat中有一個自定義可拖動指令。 我想在拖動每個圖像后存儲x,y偏移量。 因此,我需要指令來更新圖像上的字段。
return {
restrict: 'A',
scope: false,
link: function(scope, element, attrs){
element.draggable({
containment: "parent",
cursor: "crosshair",
stop: function(ev, ui) {
scope.left=ui.helper[0].style.left;
scope.top=ui.helper[0].style.top;
}
});
}
};
<div ng-repeat="image in images"
draggable
ng-style="{left:image.left,
top:image.top}">... image stuff here ...</div>
不幸的是,這不起作用,因為當ng-repeat為每個圖像項創建子范圍時,它
創建一個新的作用域,它原型繼承自父作用域,但它也將該項的值賦給子作用域的新屬性。 (新屬性的名稱是循環變量的名稱。)( https://github.com/angular/angular.js/wiki/Understanding-Scopes#ng-repeat )
我可以通過更改引用來使用循環變量名來使指令工作,因為我想要它:
scope.image.left=ui.helper[0].style.left;
scope.image.top=ui.helper[0].style.top;
但我不想將循環變量名稱硬編碼到指令中。
將循環變量名稱傳遞給指令或理想情況下,將項目值的引用直接傳遞給指令的最佳方法是什么?
在這種情況下,使用隔離范圍並使用雙向綁定將當前圖像對象傳遞給指令是很方便的。
所以HTML可以是這樣的:
<div ng-repeat="image in images" draggable="image" ng-style="{left:image.left, top:image.top}">
<!-- ... image stuff here ... -->
</div>
和指令然后:
.directive('draggable', function () {
return {
scope: {image: '=draggable'},
link: function (scope, element, attrs) {
element.draggable({
containment: "parent",
cursor: "crosshair",
stop: function (ev, ui) {
scope.image.left = ui.helper[0].style.left;
scope.image.top = ui.helper[0].style.top;
}
});
}
};
});
這樣您就不再對變量名稱進行硬編碼,並使指令更具可重用性。 例如,您可以將HTML更改為ng-repeat="img in images" draggable="img"
但指令代碼將保持不變。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.