[英]Access scope variable inside script tag
我对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;
});
});
如何在数据变量中访问变量? 这个:
values: [{{i.used_mb}}, {{i.free_mb}}],
我想要的是为项目中的每个i设计一个使用Plotly的图形。 非常感谢你。
这是我这样做的方法:
<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函数。
避免将可操纵DOM的代码放入控制器中。 而是创建一个自定义指令 :
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.