【发布时间】:2017-09-12 23:26:18
【问题描述】:
因为 angular 没有原生拖放支持,所以我正在编写一个指令,使不同的拖动事件以 angular 方式工作。
我通过创建将绑定和执行我的事件处理程序的自定义属性来做到这一点。
包含带有自定义 dragstart 处理程序的元素的指令
这是我想将 customDragStartHandler 属性指令放入的模板:
myApp.directive("myDraggableList", function() {
return {
template: '<ul> <li ng-repeat = "item in listItems"
draggable = "true"
customDragStartHandler = "handleDragStart">
{{item.label}}
</li>
</ul>',
link: function(scope, element, attrs) {
scope.handleDragStart = function(event) {
// handle dragstart event
}
}
}
})
自定义 dragstart 事件指令
myApp.directive("customDragStartHandler", function() {
return {
restrict: "A",
scope: {
"customDragStartHandler": "&"
},
link: function(scope, element, attrs) {
element.bind('dragstart', function(event) {
scope.customDragStartHandler( {event: event} )
})
}
}
})
问题:处理程序没有在链接函数的范围内被调用
在正常情况下,我期望并希望在链接函数的范围内调用事件处理程序。即如果链接函数中有一个变量,那么我希望它在处理程序的范围内可用。
让我们在链接函数中添加一个说明性变量mySetupVariable 来显示:
myApp.directive("myDraggableList", function() {
return {
template: '<ul> <li ng-repeat = "item in listItems"
draggable = "true"
customDragStartHandler = "handleDragStart">
{{item.label}}
</li>
</ul>',
link: function(scope, element, attrs) {
var mySetupVariable = 'a string I want to reference'
scope.handleDragStart = function(event) {
// I expect to be able to access mySetupVariable here
// but instead the scope is empty and `.this` represents
// the scope of the template
//
console.log mySetupVariable // => undefined
console.log this.scope // => scope of template
}
}
}
})
问题是我做不到。 handleDrag 函数是在模板范围内调用的,而不是链接函数。
如何使处理程序在链接函数而不是模板的范围内执行?
【问题讨论】:
标签: javascript angularjs angularjs-directive