2017-04-02 26 views
0
<canvas class="chart chart-bar" chart-data="data" chart-labels="labels" 
        chart-options="options" chart-series="series" chart-click="onclick"></canvas> 

'use strict'; 

var app = angular.module('examples', ['chart.js', 'ui.bootstrap']); 

app.controller('StackedBarCtrl', ['$scope', function ($scope) { 
    $scope.labels = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']; 
    $scope.type = 'StackedBar'; 
    $scope.series = ['2015', '2016']; 
    $scope.options = { 
     scales: { 
     xAxes: [{ 
      stacked: true, 
     }], 
     yAxes: [{ 
      stacked: true 
     }] 
     } 
    }; 

    $scope.onclick = function(points,evt) 
    { 
     console.log("evt "+points[0]["_modal"]["datasetLabel"]); 
    } 

    $scope.data = [ 
     [65, 59, 90, 81, 56, 55, 40], 
     [28, 48, 40, 19, 96, 27, 100] 
    ]; 
}]); 

如果我上杆28我没有得到的值2016点击图表单击,因为点阵列中的onclick函数返回,我对每个堆2个对象无法弄清楚如何获得价值2016年之前,没有任何标志,表示该酒吧是在无法获取系列谷在角堆积条形图

回答

1

的第二个参数传递给你的onclick回调点击含有活性元素的数组,每个项目包含_datasetIndex_index

array[1] 
[Element] 
    _datasetIndex:0 
    _index: 0 

使用这些值,你可以得到你需要

$scope.onclick = function(event, elems) 
{ 
    var datasetIndex = elems[0]._datasetIndex; 
    console.log("evt " + $scope.series[datasetIndex]); 
} 

请的价值,是指chartjs docsthis issue与您问题相关

UPDATE

看起来是有点棘手与叠置条图表。解决的办法是找到使用Chart.helpers

$scope.$on('chart-create', function(event, instance){ 
    // used to obtain chart instance 
    $scope.chart = instance.chart; 
}); 
$scope.onclick = function(elements,e) 
{ 
    // helper function that translates an event to a position in canvas coordinates 
    var pos = Chart.helpers.getRelativePosition(e, $scope.chart); 

    // inRange is the function on the chart element that is used for hit testing 
    var intersect = elements.find(function(element) { 
    return element.inRange(pos.x, pos.y); 
    }); 
    if(intersect){ 
    alert('You clicked ' + $scope.labels[intersect._index] + ' ' + $scope.series[intersect._datasetIndex]);  
    } 
} 

这里最接近点击的杆在这种情况下,工作plunkr

+0

所以,如果我的值“28”单击,elems的数组包含2个有源元件elems的具有[0]标签=“星期一”和数据标签=“2015”的值为65和elems [1] withdatsetlabel =“2016”,标签=“星期一”为值28,datasetIndex为0,索引也为0,在本例中为您已经提到elemns [0] ._ datasetIndex是0,但我仍然没有得到系列值“2016”,因为我点击了值28 – Ullas

+0

我明白你的关注。如果您已阅读[问题链接]上的主题(https://github.com/chartjs/Chart.js/issues/3478#issuecomment-254185261),则表示“新”最近“模式效果更好,并且保证只返回一个元素“。所以你应该没有问题,因为默认模式是“最接近”的 –

+0

你可以通过提供示例代码来帮助我,如果可能的话,我已经在上面使用过 – Ullas