长话短说:
我有以下文件结构:
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.js的load
和unload
方法完成的。
如果写在getData()
内,在这里工作的行,它可以正常工作,但每次运行代码时都会这样做,我想只在我点击时才这样做一个按钮。
问题是我无法将此功能粘贴到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()
这是控制器上的一个方法,应该在触发ng-click
时调用。
该方法在控制器中,如下所示:
updateLegendChart(){
RandomCtrl.chartStuff.chart.unload("ID-1234");
}
错误说:
TypeError:无法读取未定义的属性“图表”
知道如何正确调用该功能吗?
答案 0 :(得分:1)
在$onInit
内嵌'此'关键字是指$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:无法读取未定义的属性'图表'
updateLegendChart(){
RandomCtrl.chartStuff.chart.unload("ID-1234");
}
如果你尝试直接传递RandomCtrl,你应该没问题。
$onInit() {
getData.call(null, RandomCtrl);
}
答案 1 :(得分:0)
为了使其按预期工作,应将RandomCtrl
替换为this
updateLegendChart()
方法,如下所示:
updateLegendChart(siteNames){
this.chartStuff.chart.unload(siteNames);
}
它不需要修改$onInit()
方法,应该让它原样