因为angular没有本机拖放支持,所以我正在编写一个指令,使不同的拖动事件以有角度的方式工作。
我这样做是通过创建一个自定义属性来绑定并执行我的事件处理程序。
这是我想将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
}
}
}
})
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函数在模板范围内调用,而不是在链接函数中调用。
如何使处理程序在链接函数的范围内而不是模板中执行?
答案 0 :(得分:1)
您可以bind()
使用
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
}.bind(this)