我已经在 Controller 内创建了一个带有对象的项目列表
$scope.devices = [
{"id": 0, "name": "sw", "class": 'sw' },
{"id": 1, "name": "mlr", "class": 'mlr'},
{"id": 2, "name": "lvm", "class": 'lvm'},
{"id": 3, "name": "ltc", "class": 'ltc'},
{"id": 4, "name": "fr", "class": 'fr'},
{"id": 5, "name": "cap", "class": 'cap'}
];
和我的 HTML 中的 ng-repeat
<li ng-repeat="device in devices" ng-click="selected(device.id)"></li>
我可以跟踪通过绑定(bind)到我的 ng-click
的 $scope.selected
点击的项目,这是基本的。
但是,稍后在指令中,当 Even 触发时怎么办?如何从元素收集信息?具体来说是它来自的原始对象ID?
// A device is grabbed
ums.directive('draggable', function (){
return function ($scope, element, attr){
// restrict: "A",
// link: function (){}
var el = element[0];
el.draggable = true;
el.addEventListener(
'dragstart',
function(e) {
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('Text', this.id);
this.classList.add('drag');
// when this event is fired I want the corresponding object id from $scope.devices
console.log(el.$scope.device.id); // my first inclination
return false;
},
false
);
}
})
最佳答案
ng-repeat
指令为添加到 DOM 的每一行创建一个范围。每个作用域都会有由 ng-repeat 设置的特殊属性。
来自文档:
The
ngRepeat
directive instantiates a template once per item from a collection. Each template instance gets its own scope, where the given loop variable is set to the current collection item, and$index
is set to the item index or key.
作用域继承自$parent
作用域。在指令的链接函数中,您可以使用 scope.$parent.devices[scope.$index]
来访问原始文件,但它也在本地范围内。
有关更多信息,请参阅AngularJS ngRepeat API Reference .
更新示例
此示例显示指令获取 $index 并发出自定义事件供 Controller 使用。
指令
ums.directive('draggable', function (){
function postLinkFn (scope, elem, attr){
console.log("instantiating directive");
elem.prop('draggable', true);
elem.on ('dragstart',
function(e) {
elem.addClass('drag');
console.log("dragstart index =", scope.$index);
//emit event for controller
scope.$emit("umsDragstart", e);
return false;
}
);
}
return postLinkFn;
})
在 Controller 中
$scope.$on("umsDragstart", function ($event, rawEvent){
console.log($event);
console.log(rawEvent.x, rawEvent.y);
console.log("umsDragstart id =", $event.targetScope.device.id);
});
请注意,该示例在 postLinkFn
的 elem
参数上使用 jqLite
方法。这些方法记录在 AngularJS angular.element API Reference 中.
$on
和 $emit
方法记录在 AngularJS $rootScope.scope API Reference - $on 中。和 API Reference - $emit .
关于javascript - 使用 ng-repeat 创建元素后正确跟踪对象 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34442298/