我有一个关于angularjs的问题。
我有这样的HTML:
<html>
<body ng-controller="datafileController">
<div class="container">
<center><h1>Datafiles</h1></center>
<div class="row" ng-repeat="i in datafile.items">
<div class="col-sm-8">
<p>Total MB: {{i.total_mb}}</p>
<p>Used MB: {{i.used_mb}}</p>
<p>Free MB: {{i.free_mb}}</p>
<br>
<br>
</div>
<div class="col-sm-4">
<div id="myDiv"></div>
<script>
var data = [{
values: [{{i.used_mb}}, {{i.free_mb}}],
labels: ['Free MB', 'Used MB'],
type: 'pie'
}];
Plotly.newPlot('myDiv', data);
</script>
</div>
</div>
</div>
</body>
</html>
我的控制器是这样的:
aebdApp.controller('datafileController', function($scope, $http) {
$http.get('http://127.0.0.1:8083/json/datafiles.json').
then(function(response) {
$scope.datafile = response.data;
});
});
我如何在数据var访问i变量?这样:
values: [{{i.used_mb}}, {{i.free_mb}}],
我想要的是使用Plotly为每个项目设计图表。 非常感谢你。
答案 0 :(得分:0)
这是我这样做的方法:
<html>
<body ng-controller="datafileController">
<div class="container">
<center><h1>Datafiles</h1></center>
<div class="row" ng-repeat="i in datafile.items">
<div class="col-sm-8">
<p>Total MB: {{i.total_mb}}</p>
<p>Used MB: {{i.used_mb}}</p>
<p>Free MB: {{i.free_mb}}</p>
<br>
<br>
</div>
<div class="col-sm-4">
<div id="myDiv_{{$index}}"></div>
</div>
</div>
</div>
<script>
aebdApp.controller('datafileController', function ($scope, $http, $timeout) {
$http.get('http://127.0.0.1:8083/json/datafiles.json').then(function (response) {
$scope.datafile = response.data;
$timeout(function () {
$scope.datafile.forEach(function (i, index) {
var data = [{
values: [i.used_mb, i.free_mb],
labels: ['Free MB', 'Used MB'],
type: 'pie'
}];
Plotly.newPlot('myDiv_' + index, data);
});
}, 1000);
});
});
</script>
</body>
</html>
基本上,使用隐式$index
变量并使用$timeout
注入函数。我不确定是否需要$ timeout功能。
答案 1 :(得分:0)
避免在控制器中放置操纵DOM的代码。而是创建一个custom directive:
app.directive("plotly", function() {
return {
link: postLink
};
function postLink(scope,elem,attrs) {
scope.$watch(attrs.plotly, function(i) {
if (i) {
var data = [{
values: [{{i.used_mb}}, {{i.free_mb}}],
labels: ['Free MB', 'Used MB'],
type: 'pie'
}];
Plotly.newPlot(elem[0], data)
};
});
}
}
<div class="row" ng-repeat="i in datafile.items">
<div class="col-sm-8">
<p>Total MB: {{i.total_mb}}</p>
<p>Used MB: {{i.used_mb}}</p>
<p>Free MB: {{i.free_mb}}</p>
<br>
<br>
</div>
<div class="col-sm-4">
<div id="myDiv{{$index}}" plotly="i"></div>
</div>
</div>