我有这个非常烦人的问题,我觉得我知道它为什么会引起但是不能为我的生活解决它。也许是因为我不了解编程的基本规则......
让我演示一下这个问题:
HTML:
<!DOCTYPE html>
<html lang="en" ng-app="angularApp">
<head>
<meta charset="utf-8">
<link href="/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<section>
<div class="container">
<div class="row">
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Wall</h3>
</div>
<div class="panel-body">
<div ng-controller="wallPosts">
<div class="panel panel-default post" ng-repeat="post in posts">
<div class="panel-body">
<div class="row">
<div class="col-sm-3">
<canvas id="pie" class="chart chart-pie" chart-data="data" chart-labels="labels" chart-options="options">
</canvas>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div><!-- col-md-8 end -->
</div>
</div>
</section>
<!-- Bootstrap core JavaScript-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="/jsLib/bootstrap.js"></script>
<script src="/jsLib/angular.min.js"></script>
<script src="/angular/angularApp.js"></script>
<script src="/jsLib/chart.js/dist/Chart.min.js"></script>
<script src="/jsLib/angular-chart.js/dist/angular-chart.min.js"></script>
<script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
</script>
</body>
</html>
角度控制器:
var angularApp = angular.module('angularApp', ['chart.js']);
angularApp.controller('wallPosts', ['$scope', '$http', function($scope, $http){
$scope.posts = [];
$scope.labels = ["Agree", "Disagree"];
$scope.data = [];
$http.get('/api/posts')
.success(function(res){
$scope.posts = res.posts;
//$scope.data = [100, 500];
$scope.data = [res.posts.agreeCounter, res.posts.disagreeCounter];
})
.error(function(data, status){
console.log(data);
});
}]);
API响应如下所示:
"posts": [
{
"postID": "postID1233",
"title": "testTitle",
"description": "testDescription",
"agreeCounter": 100,
"disagreeCounter": 50
}]
问题在于&#34;画布&#34;似乎是在没有我通过的数据的情况下立即生成。当我将$ scope.data作为[100,50](静态)传递时,它可以工作。
顺便说一句,res.posts的工作原理正如我用post.title,post.description等测试的那样(它也有post.agreeCounter)所以这不是问题。
那么我该如何解决这个问题呢?任何输入都会有所帮助。
再次感谢, 砂眼
答案 0 :(得分:1)
似乎每个帖子都需要一个图表,对吗?
更改模板以获取每个帖子的数据
<div class="panel panel-default post" ng-repeat="post in posts">
<div class="panel-body">
<div class="row">
<div class="col-sm-3">
<canvas class="chart chart-pie"
chart-data="post.data"
chart-labels="labels"
chart-options="options"
></canvas>
</div>
</div>
</div>
</div>
为每个投标帖子填充post.data
$http.get('/api/posts')
.success(function(res) {
$scope.posts = res.posts;
// populate post.data
$scope.posts.forEach(function(post) {
post.data = [post.agreeCounter, post.disagreeCounter];
});
})
文档中的BTW ID 必须是唯一的。您不应在id="pie"
内使用静态ID(ng-repeat
)。它将生成具有相同ID的多个节点。