2017-04-02 52 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