Angularjs动态加载ECharts(一)

时间:2022-07-23
本文章向大家介绍Angularjs动态加载ECharts(一),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

今早发现,directive写的echarts组件,虽然能够获取到Controller中的数据,但是当我使用$http请求到的数据,想传到directive却总是获取不到,知道这是异步问题,图表加载后,数据才请求到,所以图表加载不了数据

解决方法

使用ng-if,判断,如果有数据才显示,完美解决

<realtem-data ng-if="data" id="temdata" legend="legend" item="item" data="data"></realtem-data>

其余代码

controller代码

app.controller("temdataCtrl", function($scope, $http, $log) {
    $http({
        method: "get",
        url: "http://..:3000/tem",
        headers: {
            "content-type": "application/json"
        }
    }).then(function(req) {
        // console.log(req.data)
        $scope.data = req.data
    })
})

directive代码

 app.directive('realtemData', function() {
     return {
         scope: {
             id: "@",
             data: "="
         },
         restrict: 'E',
         template: '<div class="real-data-charts"></div>',
         replace: true,
         link: function($scope, element, attrs, controller) {
             var option = {
                 color: ['#CD3700'],
                 tooltip: {
                     trigger: 'axis',
                     axisPointer: { // 坐标轴指示器,坐标轴触发有效
                         type: 'shadow' // 默认为直线,可选为:'line' | 'shadow'
                     }
                 },
                 legend: {
                     data: ['温度'],
                 },
                 label: {
                     normal: {
                         show: true
                     }
                 },
                 grid: {
                     left: '3%',
                     right: '4%',
                     bottom: '3%',
                     containLabel: true
                 },
                 xAxis: [{
                     type: 'category',
                     data: [1, 2, 3, 4, 5],
                     axisTick: {
                         alignWithLabel: true
                     }
                 }],
                 yAxis: [{
                     type: 'value'
                 }],
                 series: [{
                     name: '温度',
                     type: 'line',
                     barWidth: '60%',
                     data: $scope.data
                 }]
             };
             var myChart = echarts.init(document.getElementById($scope.id), 'macarons');
             myChart.setOption(option);
         }
     };
 });

图片.png

注意 发现如果多个数据的话,可能这么操作会导致图表上只有一个数据显示 所以我把所有的数据都放到一个对象中,然后ng-if只判断这个对象即可