gpt4 book ai didi

javascript - 从 AngularJS 中的 Controller 调用 html 页面上的函数

转载 作者:行者123 更新时间:2023-12-03 03:08:46 26 4
gpt4 key购买 nike

长话短说:

我有以下文件结构:

class RandomCtrl {
constructor(randomService) {
this.randomService = randomService;
...
}

$onInit() {
getData.call(null, this);
}

...

}

updateLegendChart(){
RandomCtrl.chartStuff.chart.unload("ID-1234");
}

function getData(RandomCtrl) {

RandomCtrl.ChartDataService.getData(DemandCtrl.dataParams).then(result => {
RandomCtrl.result = result.data;
RandomCtrl.siteNames = result.data.map(element => element.SiteName);
RandomCtrl.keys = Object.keys(result.data);
RandomCtrl.chartStuff = getChart(result.data);
RandomCtrl.chartStuff.chart.unload("ID-1234"); ////<-HERE IT WORKS!!!

}).catch((e) => {
console.log(e);
});
}


function getChart(data) {
const chartOptions = getWeekHourlyOptions(data);

const allCols = [].concat(chartOptions.dataColumns);

...
return {allCols, chart};
}

...

RandomCtrl.$inject = ['randomService'];

export const Random = {
bindings: {
data: '<',
siteNames: '<'
},
templateUrl: randomPageHtml,
controller: RandomCtrl
};

我有一个包含多行的图表,每行代表一个站点,我想在单击图例部分中的名称时删除或添加它们。

我通过使用Billboard.jsloadunload方法来做到这一点.

如果将其写入 getData() 中,即 HERE IT WORKS 行,它可以工作,但每次运行代码时它都会这样做,我想做仅当我单击按钮时才会出现。

问题是我无法将此功能与 ng-click 粘合到 html 页面中。

这是 html 页面:

<div class="demand page">
<div class="chart-legend-container">
<div ng-repeat="site in $ctrl.keys">
<chart-legend site="$ctrl.siteNames[site]" keys= "$ctrl.keys"></chart-legend>
<button ng-click="$ctrl.updateLegendChart()">CLICK ME</button>
</div>
<div>
</div>

我的方法是使用 updateLegendChart() 这是 Controller 上的一个方法,当触发 ng-click 时应该调用它。

该方法位于 Controller 中,如下所示:

updateLegendChart(){
RandomCtrl.chartStuff.chart.unload("ID-1234");
}

错误提示:

TypeError: Cannot read property 'chart' of undefined

知道如何正确调用该函数吗?

最佳答案

$onInit 钩子(Hook)“this”关键字引用 $onInit 上下文,而不是 RandomCtrl

$onInit() {
getData.call(null, this);
}

可能是您不想做的事情,因为这样您就会将所有这些属性(结果、chartStuff 等)附加到错误的对象。

..
//here RandomCtrl is still $onInit context, and not the the class context
RandomCtrl.chartStuff = getChart(result.data);

因此,当您调用updateLegendChart()时,RandomCtrl没有任何chartStuff字段,因此您会收到异常“TypeError:无法读取未定义的属性'chart'”

updateLegendChart(){
RandomCtrl.chartStuff.chart.unload("ID-1234");
}

如果你尝试直接传递 RandomCtrl 应该没问题。

$onInit() {
getData.call(null, RandomCtrl);
}

关于javascript - 从 AngularJS 中的 Controller 调用 html 页面上的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47040606/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com