我在用如下方法在angular中用D3.js 画图。第一部分是实现画图功能的。涉及到directive.js写指令,controller.js中写作用域scope,在页面中写指令的p三个部分。我的问题是:在把contoller.js中的作用域scope的值放入json中访问时,无法画出相同的图形了。
首先贴上能实现画图功能,但是scope值写在本地的代码:
1、directive.js
2、controller.js
3、left.html
以上方法便能画出 angular+d3.js的图,如下~
可是,问题来了,想把controller.js 中的数据,变成$http.get("grade.json").success(function(data)这样请求的文件内的数据。
grade.json的数据如下:
会出现错误。。。
为什么呀。。
ringa_lee2017-05-15 17:03:52
Since instructions are used, try to use independent scopes to maintain the independence of instructions. In your situation, you can change it to this
.directive('linearChart', function () {
return {
scope: {
chartData: '=chartData'
},
restrict: 'EA',
template: '<svg width="400" height="200"></svg>',
link: function (scope, element, attrs) {
scope.$watch('chartData', function (newData, oldData) {
if (!newData) return;
drawLineChart(newData);
});
function drawLineChart(data) {
//todo
}
}
}
})
迷茫2017-05-15 17:03:52
It’s done. . . You can print the corresponding value of your salesDataToPlot
,看看是不是null
,报错提示应该就是那里的原因;还有指令与控制器之间的数据传递要么使用独立作用域,然后使用scope
parameter binding in the instruction; or use the inherited scope.
滿天的星座2017-05-15 17:03:52
This is asynchronous during the $http request, and the directive is already being compiled when the dom is loaded. At that time, salesData is of course undefined.
You should be like this
$http.get(api)
.then(function(res) {
appendChart(); //这时才把指令加载到dom里去
})
= = OMG, can the questioner ask the question without directly posting the screenshot of the code? segmentfault supports markdown syntax, dear