how to add click event to angular js directive for

2019-08-06 00:45发布

问题:

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