【发布时间】:2015-11-06 20:27:57
【问题描述】:
我在 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;
但我不想将循环变量名称硬编码到指令中。
将循环变量名称传递给指令的最佳方法是什么,或者理想情况下,将项目值的引用直接传递给指令的最佳方法是什么?
【问题讨论】:
标签: javascript angularjs angularjs-directive angularjs-scope angularjs-ng-repeat