简体   繁体   中英

How to use AngularJs scope in an external javascript function

I try to draw a chart using Chart.js . The data comes from my API and I know the format is OK. I don't know how to pass the data retieved from the API to the javascript function.

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 ? or how is the right way to do this?

Use the existing library of Chart.js which has already converted code in angularise way.

Just you need to include angular-chartjs.js

And then inject to your model angular.module('myApp', ['chart.js'])

After that you can use it as attribute anywhere you want.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM