我试图用angularjs和d3js绘制动态加载数据的条形图。 当我打电话
$http.get('groups/all_groups.json').then($scope.groups = [10,20,30,40,60, 80, 20, 50]);
它的工作,我可以在我的指示绘制的数据,但是当我试图
$http.get('groups/all_groups.json').then(function (response) { $scope.groups = [10,20,30,40,60, 80, 20, 50];} // eventually, here is dynamic data
然后我得到一个错误:
类型错误:在Array.d3_selectionPrototype.data(012)处无法读取绑定(http://d3js.org/d3.v2.js:3727:45) 处的未定义 的属性“长度”) at directiveDefinitionObject.link
我相信指令中的d3js范围没有设置,但是如何将http-response导出到d3js?
编辑: 这里是指令:
.directive('barsChart', function ($parse) {
//explicitly creating a directive definition variable
//this may look verbose but is good for clarification purposes
//in real life you'd want to simply return the object {...}
var directiveDefinitionObject = {
//We restrict its use to an element
//as usually <bars-chart> is semantically
//more understandable
restrict: 'E',
//this is important,
//we don't want to overwrite our directive declaration
//in the HTML mark-up
replace: false,
//our data source would be an array
//passed thru chart-data attribute
scope: {data: '=chartData'},
link: function (scope, element, attrs) {
//in D3, any selection[0] contains the group
//selection[0][0] is the DOM node
//but we won't need that this time
var chart = d3.select(element[0]);
//to our original directive markup bars-chart
//we add a div with out chart stling and bind each
//data entry to the chart
chart.append("div").attr("class", "chart")
.selectAll('div')
.data(scope.data).enter().append("div")
.transition().ease("elastic")
.style("width", function (d) {
return d + "%";
})
.text(function (d) {
return d + "%";
});
//a little of magic: setting it's width based
//on the data value (d)
//and text all with a smooth transition
}
};
return directiveDefinitionObject;
html元素:
<bars-chart chart-data="groups"></bars-chart>
和控制器:
.controller('View2Ctrl', ['$scope', '$http',
function ($scope, $http) {
$http.get('groups/all_groups.json').then(function (response) {
$scope.groups = [10,20,30,40,60, 80, 20, 50];
console.log($scope.groups);
}, function(response){
console.log('error');
});
}])
您没有向我们展示足够的代码。 – Adam 2014-12-19 01:44:31