【问题标题】:How do I change the scope a method is executed in in Angular?如何更改在 Angular 中执行方法的范围?
【发布时间】: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


    【解决方案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)
    

    【讨论】:

    • 所以我尝试了这个,它确实将this 变成了很棒的链接功能。但是它似乎不尊重链接功能的正常关闭效果,mySetupVariable 不再可用。正常的scopeelementattrs 变量也不是。你对此有什么想法吗?
    • 您也可以在link函数中使用var linkSelf = this;,然后引用linkSelf.mySetupVariable。另见gist.github.com/jashmenn/b306add36d3e6f0f6483
    猜你喜欢
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-19
    相关资源
    最近更新 更多