在点击事件上获取 echarts 以更改附加到 angularjs 中的 $scope 的变量值

get echarts on click event to change value of variable attached to $scope in angularjs

我在我的angularjs项目中使用了echarts。如果可能的话,我宁愿不必使用 ng-echarts 模块。我希望能够在图表对象上获得一个点击事件,以更改 $scope 上可用于切换 ng-show

的变量值

我在控制器中的代码是这样的:

myChart = echarts.init(document.getElementById('main'));

// code that prepares the graph data goes here
// ...

myChart.setOption(option,true); 

myChart.on('click', function(e) {

  //this works fine
  console.log(e) 

  // this does nothing
  $scope.showDiv = true //this does nothing
})

有没有办法让 $scope.showDiv = true 在视图中实际处理 <div ng-if="showDiv">test</div>

我搜索了文档和其他来源,但找不到任何东西。

问题是您没有使用 angular 的 ng-click 函数,该函数会自动将代码包装在 $apply() 中。由于您使用的是非 angular 代码,因此您需要自己执行此操作。只需在方法末尾添加 $scope.$apply() 即可。 This article 有一些关于此的有用信息。

When Do You Call $apply() Manually?

If AngularJS usually wraps our code in $apply() and starts a $digest cycle, then when do you need to do call $apply() manually? Actually, AngularJS makes one thing pretty clear. It will account for only those model changes which are done inside AngularJS’ context (i.e. the code that changes models is wrapped inside $apply()). Angular’s built-in directives already do this so that any model changes you make are reflected in the view. However, if you change any model outside of the Angular context, then you need to inform Angular of the changes by calling $apply() manually. It’s like telling Angular that you are changing some models and it should fire the watchers so that your changes propagate properly.


附带说明一下,我建议使用 ng-echartsng-click 而不是 on('click',..)。使用 angular 指令和框架使代码更易于遵循、实施和调试。

一个简单的 $scope.$apply() 就成功了。呃。

就我个人而言,我认为 ng-echarts 完全是一团糟,有 100 多行代码,所以我为 angular 1.5+ 编写了自己的代码。

它只有 20 行,可以满足您的所有需求,包括在您的 configoption 变量发生变化时(通过 $onChanges 自动检测)更新图表(动画)。

将来可能会对您或其他人有所帮助。


组件

app.component('chart', {
    bindings: {
        config      : '<',
        option      : '<'
    },
    controller: function ($element, $window) {
        let chart = echarts.init($element[0]);

        this.$onInit = function() {
            angular.element($window).on('resize', function() {
                chart.resize()
            });
        }

        this.$onChanges = function(changes) {
            chart.setOption(this.option, this.refresh);
            chart.resize();
            chart.hideLoading();
        }
    }
})

模板

<chart
    option="myChart.option" 
    config="myChart.config">
</chart>

CSS

// Fix for Bootstrap init width
chart {
    width: 100%; 
    height: 250px; 
    float: left;
}