问题描述
我有一个问题,不记得如何解决.我正在订阅来自第三方指令的回调,但未使用正确的范围进行回调.而且我的意思是,当它击中我的控制器 this
时,我实际上还无法确定其他范围,因此它无法访问任何成员变量.我如何回到我的控制器范围?
< ui-gmap-layer type ="HeatmapLayer" onCreated ="$ ctrl.heatLayerCallback"></ui-gmap-layer>
组件控制器:
heatLayerCallback(heatLayer:google.maps.visualization.HeatmapLayer){this.heatMapLayer = heatLayer;//这里的'this'不是我的控制器}
如果我将呼叫改回
< ui-gmap-layer onCreated ="$ ctrl.heatLayerCallback(layer)"></ui-gmap-layer>
然后我的回调在正确的范围(即我的控制器)上执行,但是参数 layer
丢失了;/
注释
我正在使用Typescript,Angular 1.6和Angular组件
您可以使用绑定将回调绑定到所需的上下文(您的控制器),或者只是将其存储在回调之前的另一个新变量中,并通过回调中的该变量进行访问./p>
类似的东西:
var heatLayerCallback =(function(heatLayer:google.maps.visualization.HeatmapLayer){this.heatMapLayer = heatLayer;//这里的"this"现在与在下面的"this"相同}).bind(this);//绑定到此或您想要的任何上下文
...或:
var that = this;//存储此内容或您想要的任何上下文...heatLayerCallback(heatLayer:google.maps.visualization.HeatmapLayer){that.heatMapLayer = heatLayer;
确切的语法可能会有所不同,具体取决于引用的代码所在的位置(例如,找到所需的"this",或使用任何上下文代替"this").
I have an issue and can't remember how to get around it. I am subscribing to a callback from a third party directive but not being called back with the correct scope. And by that I mean that when it hits my controller this
is actually some other scope I cant quite figure out so it cannot access any member variables. How do I get back to my controller scope?
<ui-gmap-layer type="HeatmapLayer" onCreated="$ctrl.heatLayerCallback"></ui-gmap-layer>
Component Controller:
heatLayerCallback(heatLayer: google.maps.visualization.HeatmapLayer) {
this.heatMapLayer = heatLayer;
// 'this' here is not my controller
}
If I change the call back to
<ui-gmap-layer onCreated="$ctrl.heatLayerCallback(layer)"></ui-gmap-layer>
Then my callback executes on the right scope (i.e. my controller) but the parameter layer
is lost ;/
Notes
I am using Typescript, Angular 1.6 and Angular Components
You could use bind to bind the callback to the context you want (your controller) or simply store it in another new variable before the callback and access it by that variable within the callback.
Something like:
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
...or:
var that = this; // store this or whatever context you want
...
heatLayerCallback(heatLayer: google.maps.visualization.HeatmapLayer) {
that.heatMapLayer = heatLayer;
The precise syntax may vary depending on where your quoted code lives (e.g. find where "this" is what you want, or use whatever context instead of "this").
这篇关于错误范围的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!