how to add click event to angular js directive for plotting flot bar chart

馋奶兔 提交于 2019-12-11 10:40:09

问题


I am pretty new to angularjs and flot charts. I am trying to add click events to my stacked bar charts so that once I click a stack it displays the categories information but I am not sure if am doing it right. Please help take a look

I already plot my chart in angularjs directive

see http://jsfiddle.net/6h1gL2sh/10/ here

App.directive('chart', function () {
return {
    restrict: 'EA',
    link: function (scope, elem, attrs) {
        var chart = null,
            options = {
                series: {
                    stack: true,
                    bars: {
                        show: true,
                        clickable: true,
                        barWidth: 0.1,
                        align: "center"
                    }
                },
                axisLabels: {
                    show: true
                },

                xaxis: {
                    axisLabel: 'Products',
                    axisLabelUseCanvas: true,
                    axisLabelFontSizePixels: 12,
                    axisLabelPadding: 5,
                    mode: "categories",
                    tickLength: 0
                },
                yaxis: {
                    axisLabel: 'Pass/Fail Count',
                    axisLabelUseCanvas: true,
                    axisLabelFontSizePixels: 12,
                    axisLabelPadding: 5

                },
                grid: {
                    hoverable: true,
                    clickable: true
                }

            }
        var data = scope[attrs.ngModel];
        scope.$watch(attrs.ngModel, function (v) {
            if (!chart) {
                chart = $.plot(elem, v, options);
                elem.show();
            } else {
                chart.setData(v);
                chart.setupGrid();
                chart.draw();
            }
        });
        $(elem).bind("plotclick", function (event, pos, item) {
            scope.$apply(function () {
                if (item) {
                    scope.dis = item.series.xaxis.categories[item.dataIndex].label

                }
            });
        });

    }
};

});


回答1:


Since you're trying to get an object's Key by value, you can't really access it as an array using bracket notation. I used a function that can be found on this SO question: JavaScript object get key by value

Then, I simply changed your click part to this:

elem.bind("plotclick", function (event, pos, item) {  
      if(item){
            scope.dis= getKeyByValue(item.series.xaxis.categories, item.dataIndex);
            scope.$apply();
      }
});

Fiddle



来源:https://stackoverflow.com/questions/29587038/how-to-add-click-event-to-angular-js-directive-for-plotting-flot-bar-chart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!