我认为你应该通过服务传递数据。这是我正在做的事情的版本:
http ://plnkr.co/edit/56TAdPTMt5nwnMwhErQM?p=preview
app.controller('MyCtrl', function($scope,data) {
var columns = [{ 'string' :'Topping' }, {'number' : 'Slices'}],
rows = [[ 'User', 12 ], ['Administrator', 4], ['Moderator', 7]];
$scope.data = data.get(columns,rows);
});
app.service('data',function() {
return {
get : function(_columns,_rows) {
var _data = new google.visualization.DataTable();
for(var i=0;i < _columns.length;i++){
for(k in _columns[i]) {
_data.addColumn(k,_columns[i][k]);
}
}
_data.addRows(_rows);
return _data;
}
}
});
app.directive('chart', function() {
return {
restrict: 'A',
link: function($scope, $elm, $attrs) {
var chart,data,
// Set chart options
options = {'title':'ROLE',
'width':400,
'height':300};
$scope.$watch(function() {
return JSON.stringify($scope[$attrs.chart]);
},
function(_d) {
if(typeof _d !== 'undefined') {
data = $scope[$attrs.chart]
// Instantiate and draw our chart, passing in some options.
chart = new google.visualization.PieChart($elm[0]);
chart.draw(data, options);
}
});
}
}
});