在angular中使用json数组整数

using a json array integer in angular

本文关键字:json 数组 整数 angular      更新时间:2023-09-26

我想在一个范围内导入一个json数组的整数。数据用于填充d3条,但当它不起作用时!它将数组置于作用域中。因为当我在html中做{{data}}时,它显示了数组,但不能利用它的d3条,请帮助!!

 angular.module('myApp', [])
//.controller('SalesController', ['$scope', function($scope, $http){
.controller('SalesController', function($scope, $http) {
/* $http.get('js/todos2.json')
.then(function(res){
      $scope.data = res.data;              
});*/
/*$http({method: 'GET', url: 'js/todos2.json'}).success(function(data)
{
$scope.data = data; // response data 
});*/
$http.get('js/todos2.json').success(function(data) {
   $scope.data = data;
});
/*$scope.data = [Math.random(),12,6,8,15];*/
/*$scope.data = 7*/
$scope.text = ('klopm');
 //parseInt(data)
}).directive('bars', function ($parse) {
  return {
     restrict: 'E',
     replace: true,
     template: '<div id="chart"></div>',
     scope:{data: '=data'},
     link: function (scope, element, attrs) {
       var data = scope.data;
       function drawBars() {
          var chart = d3.select('#chart')
         .append("div").attr("class", "chart")
         .selectAll('div')
         .data(data[0]).enter()
         .append("div")
         .transition().ease("elastic") //had la ligne bantli zayda na9ssa b3da pr l'affichage il faut savoir a quoi sert
         .style("width", function(d) { return d + "%"; })
         .text(function(d) { return d + "%"; });
       }
       drawBars();
     } 
  };
});

由于您从json文件中获取数据,因此$scope.data不会立即填充,因此您需要在绘制图表之前观察它以确保它已填充。在您的指令定义中,而不是立即调用drawBars()函数,您需要确保有数据。像这样的

scope.$watch('data', function(){
    if(!scope.data) return; //If there is no data, do nothing
    //now call your draw function
    drawBars();
})