angularjs - 回调错误范围

标签 angularjs typescript angular-google-maps

我遇到了问题,但不记得如何解决它。我正在订阅来自第三方指令的回调,但没有以正确的范围回调。我的意思是,当它到达我的 Controller 时 this 实际上是我无法弄清楚的其他范围,因此它无法访问任何成员变量。如何返回我的 Controller 范围?

<ui-gmap-layer type="HeatmapLayer" onCreated="$ctrl.heatLayerCallback"></ui-gmap-layer>

组件 Controller :

heatLayerCallback(heatLayer: google.maps.visualization.HeatmapLayer) {
    this.heatMapLayer = heatLayer;
    // 'this' here is not my controller
}

如果我将调用改回

<ui-gmap-layer onCreated="$ctrl.heatLayerCallback(layer)"></ui-gmap-layer>

然后我的回调在正确的范围(即我的 Controller )上执行,但参数layer丢失了;/

注释

我正在使用 Typescript、Angular 1.6 和 Angular Components

最佳答案

您可以使用bind将回调绑定(bind)到您想要的上下文(您的 Controller ),或者只是将其存储在回调之前的另一个新变量中,并通过回调中的该变量访问它。

类似于:

var heatLayerCallback = (function(heatLayer: google.maps.visualization.HeatmapLayer) {
    this.heatMapLayer = heatLayer;
    // 'this' here is now the same as the 'this' outside/below
}).bind(this); // bind to this or whatever context you want

...或:

var that = this; // store this or whatever context you want
...
heatLayerCallback(heatLayer: google.maps.visualization.HeatmapLayer) {
    that.heatMapLayer = heatLayer;

精确的语法可能会有所不同,具体取决于您引用的代码所在的位置(例如,找到您想要的“this”,或者使用任何上下文而不是“this”)。

关于angularjs - 回调错误范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45508846/

相关文章:

angular6 - 如何在 Angular 6 中使用 geohash

javascript - 是否可以计算 Angular 谷歌地图中两个标记之间的距离?

javascript - 在AngularJS中的指令中使用服务函数

javascript - angularjs $watch 获取已更改数组项的索引

Angular2 authguards 执行异步函数失败

angular - ChangeDetectionStrategy.OnPush 不符合我的预期

angularjs - 使用等待时 Node 响应中的复制问题

javascript - AngularJS: Controller 收到所有数据后加载templateUrl

typescript - Typescript 可以导入 Webpack UMD 吗?

javascript - 一张 Angular ng-map 中的标记重新出现在错误的 View 中