【问题标题】:Invoking function breaks scope调用函数打破范围
【发布时间】:2016-12-11 04:48:33
【问题描述】:

与此处相同的问题:AngularJS directive binding a function with multiple arguments

按照这个答案:https://stackoverflow.com/a/26244600/2892106

尽我所能。

这行得通:

<my-directive on-save="ctrl.saveFn"></my-directive>

与:

angular.module('app')
.controller('MyController', function($scope) {
  var vm = this;
  vm.saveFn = function(value) { vm.doSomethingWithValue(value); }
});

但是当我转换为 Typescript 并使用真正的类时,这会中断。

class MyController {
  constructor() {}

  saveFn(value) {
    this.doSomethingWithValue(value);
  }
}

在 Typescript 版本中调试时,“this”是指 Window 全局。所以我的范围不知何故搞砸了,但我不知道如何修复它。如何让“this”按预期引用 MyController?

【问题讨论】:

  • saveFn 是如何调用的?
  • 在构造函数内部,你可以做this.saveFn = this.saveFn.bind(this);。一个烦人的解决方案,但它有效。
  • 在指令调用中。所以在这样的指令中:&lt;select on-change="$ctrl.onSave()($ctrl.someValue)"&gt; 我认为这是罪魁祸首,我只是不知道为什么。
  • @CoryDanielson rad 这行得通。添加一个答案,我会把它归功于你。谢谢!

标签: angularjs angularjs-directive typescript


【解决方案1】:

所以我的范围不知何故搞砸了

使用箭头函数而不是方法。

已修复

class MyController {
  constructor() {}

  saveFn = (value) => {
    this.doSomethingWithValue(value);
  }
}

更多

https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

【讨论】:

  • 这行得通,感谢您的链接!我已经假设类上的方法不需要是胖箭头函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-26
  • 2013-06-23
  • 1970-01-01
  • 1970-01-01
  • 2013-10-03
  • 2013-03-06
相关资源
最近更新 更多