[英]How to use AngularJs scope in an external javascript function
I try to draw a chart using Chart.js . 我尝试使用Chart.js绘制图表。 The data comes from my API and I know the format is OK.
数据来自我的API,我知道格式可以。 I don't know how to pass the data retieved from the API to the javascript function.
我不知道如何将从API提取的数据传递给javascript函数。
In my controller, I got: 在我的控制器中,我得到了:
$http.get('/api/bilan').then(function(result) {
$scope.finances = result.data;
});
And here is a snippet from where I should pass data: 这是我应该传递数据的摘录:
var bilans = {
labels: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"],
datasets : [
{
data : [ TheDataFromTheApi ]
}
]
};
What shoudl I put in TheDataFromTheApi ? 我应该在TheDataFromTheApi中添加什么? or how is the right way to do this?
或如何正确地做到这一点?
Use the existing library of Chart.js which has already converted code in angularise way. 使用现有的Chart.js库,该库已经按角度方式转换了代码。
Just you need to include angular-chartjs.js
只是您需要包括
angular-chartjs.js
And then inject to your model angular.module('myApp', ['chart.js'])
然后注入模型
angular.module('myApp', ['chart.js'])
After that you can use it as attribute anywhere you want. 之后,您可以在任何需要的地方使用它作为属性。
HTML HTML
<canvas class="chart chart-bar" data="bilans.data" labels="bilans.labels" series="bilans.series"></canvas>
CODE 码
var app = angular.module("Bar_Chart", ["chart.js", "ui.bootstrap"]);
app.controller('mainCtrl', function($scope,$http) {
// you can get this data by ajax
var TheDataFromTheApi = [1,2,3,4,5,6,7,8,9,10,11,12];
$scope.bilans = {
labels: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"],
data: [TheDataFromTheApi],
series:["Months"]
};
});
Working Plunkr For your code. 工作的Plunkr为您的代码。
You should pass data into chart via an angular controller. 您应该通过角度控制器将数据传递到图表中。
Call your service ($http.get ...) into the controller, and add its result in your data, then you may be able to create your charts. 将服务($ http.get ...)调用到控制器中,然后将其结果添加到数据中,这样便可以创建图表了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.