簡體   English   中英

從AngularJS中的控制器在HTML頁面上調用函數

[英]Call function on html page from controller in AngularJS

長話短說:

我具有以下文件結構:

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的 loadunload方法來做到這一點。

如果將其寫入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() ,這是控制器上的一種方法,當觸發ng-click時應調用該方法。

該方法在控制器中,如下所示:

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

錯誤提示:

TypeError:無法讀取未定義的屬性“圖表”

知道如何正確調用該函數嗎?

$onInit鈎子內部,“ 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);
}

為了使它按預期工作,應及時更換RandomCtrlthisupdateLegendChart()這樣的方法:

updateLegendChart(siteNames){

    this.chartStuff.chart.unload(siteNames);
}

它不需要修改$onInit()方法,應該$onInit()進行操作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM