我遇到了问题,但不记得如何解决它。我正在订阅来自第三方指令的回调,但没有以正确的范围回调。我的意思是,当它到达我的 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/