我的HTML代码:
在这里,我从key
文件中检索field(JSON
)并将其显示在选项中。无论我从选择的下拉部分中选择哪个选项,我都会通过nvd3指令数据选项(data="drawData(data.repeatSelect1)"
)将该选项发送到我的角度脚本js文件中。
<div ng-controller="chartCtrl">
<label for="repeatSelect1"> Field 1: </label>
<select name="repeatSelect1" id="repeatSelect1" ng-model="data.repeatSelect1">
<option ng-repeat="(key, val) in jsondata[0]">{{key}}</option>
</select>
<br />
<strong>Selected Field:</strong> {{data.repeatSelect1}}<br />
<div class="col-md-6">
<div class="well well-lg">
<h2><kbd>Chart 1</kbd></h2>
<nvd3-pie-chart
data="drawData(data.repeatSelect1)"
showLabels="true"
labelType="percent"
showValues="false"
tooltips="true"
x="xFunction()"
y="yFunction()"
donut="true"
donutRatio=".5"
labelThreshold = "0.05"
showLegend="true"
donutLabelsOutside="false"
transitionDuration = "500">
</nvd3-pie-chart>
</div>
</div>
</div>
这是我的角度脚本代码:
angular.module('myapp').factory("test",['$http',function($http){
var obj = {};
obj.fetchdata=function(){
return $http.get('http://localhost:8080/data/my_json_file.json');
}
return obj;
}]) .controller('chartCtrl',function($scope,test){
test.fetchdata().success(function(data){
$scope.jsondata = data;
$scope.drawData = function(tobeselected){
d3.nest()
.key(function(d)
{
console.log(tobeselected);
return d.tobeselected;
})
.rollup(function(v){return v.length;})
.entries(data)
}
$scope.xFunction = function() {
return function(d) {
return d.key;
};
}
$scope.yFunction = function() {
return function(d) {
return d.values;
};
}
});
})
这是my_json_file.json
[{"Serial":"ARTUCALA","Location":null,"Date":"2014-10-02T00:00:00","Count":1,"Preset":null},{"Serial":"ZAKDJSJS","Location":null,"Date":"2014-10-02T00:00:00","Count":1,"Preset":null},{"Serial":"ARTUCALA","Location":null,"Date":"2014-10-02T00:00:00","Count":1,"Preset":null},{"Serial":"ARTUCALA","Location":null,"Date":"2014-10-02T00:00:00","Count":1,"Preset":null},{"Serial":"ZAKDJSJS","Location":null,"Date":"2014-10-02T00:00:00","Count":1,"Preset":null},{..}...]}
代码运行正常,没有任何错误。
例如:如果我在下拉列表中选择“ Serial”字段,那么它会被正确选择并显示在angularjs脚本文件中(使用console.log(tobeselected);),但是我的d3.nest选项无法正常工作。
如果我通常给
d3.nest().key(function(d){return d.Serial;}.rollup(function(v){return v.length;})
我正在正确地获得图表。请帮我解决这个问题。
最佳答案
如果要使用动态属性名称,则需要使用关联数组语法
假设tobeselected
是属性名称,则可以使用d[tobeselected]
因此请使用return d[tobeselected]
而不是d.tobeselected
当您使用d.tobeselected
时,javascript会在property
对象(不存在)上查找名为tobeselected
的实际d
,而不是等于变量property
值的tobeselected
名称。
关于javascript - 使用JSON和Angular NVD3,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35431066/