javascript - How do I change the scope a method is executed in in Angular? -
because angular has no native drag , drop support i'm writing directive makes different drag events work in angular way.
i'm doing creating custom attribute bind , execute event handler.
directive containing element custom dragstart handler
here's template want put customdragstarthandler attribute-directive into:
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 } } } }) custom dragstart event directive
myapp.directive("customdragstarthandler", function() { return { restrict: "a", scope: { "customdragstarthandler": "&" }, link: function(scope, element, attrs) { element.bind('dragstart', function(event) { scope.customdragstarthandler( {event: event} ) }) } } }) the problem: handler isn't called in scope of link function
under normal circumstances expect , want event handler called in scope of link function. i.e. if there variable in link function expect available in scope of handler.
let's add illustrative variable, mysetupvariable link function show this:
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 want reference' scope.handledragstart = function(event) { // expect able access mysetupvariable here // instead scope empty , `.this` represents // scope of template // console.log mysetupvariable // => undefined console.log this.scope // => scope of template } } } }) the problem can't. handledrag function called in scope of template, not linking function.
how can make handler execute in scope of link function rather template?
you can use bind() that
scope.handledragstart = function(event) { // expect able access mysetupvariable here // instead scope empty , `.this` represents // scope of template // console.log mysetupvariable // => undefined console.log this.scope // => scope of template }.bind(this)
Comments
Post a Comment