在Typescript中使用AngularJS控制器的范围

Lou*_*dis 2 scope angularjs typescript

情况:我最近开始使用Typescript,目前正将它集成到我的AngularJS Web应用程序中.我一直在使用'controller as'语法而不是$ scope.

问题:我似乎无法找到一个妥善的办法来取代var self = this; 我开始取代vmthis无处不在并很快让我到一个死胡同时的forEach函数中,单击事件等.

我的临时解决方案:var self = this;在每个函数中进行转换,因为据我所知,我不能全局转换它.它也不适用于所有情况.

我的问题:我错过了一些明显的东西吗?有没有更好的方法来访问控制器的范围?

Bro*_*cco 5

Fat Arrow有助于救援!!!

var self = this在TypeScript中确实没有必要使用...

胖箭头函数保留回调函数内的(词法)范围(含义):

var self = this;
fooService.doSomething()
  .then(result => {
    console.assert(this === self);  // this is valid and true
  });
Run Code Online (Sandbox Code Playgroud)

对于您的具体示例:

items.forEach((item) => {
  this.somethingElse = item; // (no need for self)
});
Run Code Online (Sandbox Code Playgroud)

注意这不是TypeScript的功能,而是ES6/ES2015的功能

进一步说明