Home  >  Q&A  >  body text

angular.js - angular封装echart自适应问题

自己封装了一个echarts

angular.module('docms')
.directive('eChart', function () {
        var eChartDirective = {
            restrict:'EA',
            template:'<p></p>',
            replace:true,
            scope:{
                option:'='
            },
            link:function(scope,eles,attrs,ctrl){
                var chart = echarts.init(eles[0]);
                scope.$watch('option',function(newOption){
                    chart = echarts.init(eles[0]);
                    chart.setOption(newOption);
                },true);
                window.addEventListener('resize',function(){
                    chart.resize();
                })



            }
        }
        return eChartDirective;
    })
<p ng-class="{true:'col-sm-12',false:'col-sm-6'}[width]">
    <e-chart option = "option"></e-chart>
</p>   

原来父元素p只占50%,后续由于ng-class调整至100%,
但是绘图在50%时已经完成了,现在我只能实现窗口大小调整时的重绘,有没有什么办法监控父元素宽度的变化,在变化时重绘cavans?

phpcn_u1582phpcn_u15822738 days ago854

reply all(1)I'll reply

  • 高洛峰

    高洛峰2017-05-15 17:13:11

    Thanks for the invitation.

    Here you can pass the variable that causes the class change of p to the eChart component.

    angular.module('docms')
    .directive('eChart', function () {
            var eChartDirective = {
                restrict:'EA',
                template:'<p></p>',
                replace:true,
                scope:{
                    option:'=',
                    forceRender:'='
                },
                link:function(scope,eles,attrs,ctrl){
                    var chart = echarts.init(eles[0]);
                    scope.$watch('option',function(newOption){
                        chart = echarts.init(eles[0]);
                        chart.setOption(newOption);
                    },true);
                    scope.$watch('forceRender',function(newOption){
                        chart.resize();
                    },true);
                    window.addEventListener('resize',function(){
                        chart.resize();
                    })
                }
            }
            return eChartDirective;
        })
    <p ng-class="{true:'col-sm-12',false:'col-sm-6'}[width]">
        <e-chart option="option" force-render="width"></e-chart>
    </p>   

    reply
    0
  • Cancelreply