javascript - 如何动态绑定(bind) Angular 图表的数据

标签 javascript json angularjs charts angularjs-controller

我正在使用 angular-charts我的应用程序中的指令,当我们最初设置数据时它运行良好。但是当我从 json 文件读取数据并将数据分配给图表时,它只生成 x 轴和 y 轴而不是图例。这是我的代码,

HTML:

 <div id="content" ng-controller="MainCtrl1" class="box-content">   
    <div style="position:relative">
     <div  data-ac-chart="'bar'"    data-ac-data="widget.data"  data-ac-config="config"  class="chart"> 
     </div>
  </div>    

这是我从文件中读取数据的模型,

 <div class="col-lg-6 col-md-6">
         <div class="form-group">
               <div  >
              <input type="file" on-read-file="showContent($fileContent)" />
         </div>
  </div>     

App.JS:

  $scope.data = {
     "series": ["Northern", "Western", "Southern", "East", "Center"],
     "data": [ {
      "x": "Mahinda",
      "y": [90, 800, 600,100,900]
    }, {
      "x": "Maithiri",
      "y": [351,439,380,800,300]
    }, {
     "x": "Others",
     "y": [140, 33,230, 879,43]
   }]
 };

这里是将数据分配给小部件,

$scope.addBarChart = function() {
  $scope.dashboard.widgets.push({
    name: "General election",
    sizeX: 110,
    sizeY: 50,
    type:"Bar",
    data:$scope.data
  });
};

这很好用,这是输出。 enter image description here

然后我从一个json文件中读取数据并分配给widget的数据对象,

  $scope.showContent = function($fileContent){
        $scope.widget.data = $fileContent;
    };

这是输出:

enter image description here

控制台也没有报错。

最佳答案

您的问题解决方案非常简单。

您使用“on-read-file”指令获取的文件内容,它以字符串格式返回文件内容。 anguar-charts 数据属性应始终采用 JSON 格式 只有你需要做 JSON.parse() recieved $fileContent to JSON。

代码

$scope.showContent = function($fileContent) {
    $scope.widget.data = JSON.parse($fileContent);;
};

我为测试创建了一个test.txt文件,并在里面写了下面的代码。

测试.txt

{
     "series": ["Northern", "Western", "Southern", "East", "Center"],
     "data": [ {
      "x": "Mahinda",
      "y": [90, 800, 600,100,900]
    }, {
      "x": "Maithiri",
      "y": [351,439,380,800,300]
    }, {
     "x": "Others",
     "y": [140, 33,230, 879,43]
   }]
 }

可以引用fiddle link获取更多信息。 希望这会对您有所帮助。

关于javascript - 如何动态绑定(bind) Angular 图表的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27792091/

相关文章:

javascript - 仅当父对象存在时才验证嵌套对象

javascript - 在 JavaScript 中解压缩 Gzip 缓冲区

javascript - 悬停时显示的说明(CSS 或 Javascript)

javascript - 在 react 循环中附加事件监听器

javascript - "Unexpected end of input"消息从简单的 POST 请求到 node.js 的响应

C# 将数据与数据库分开存储

angularjs - 如何使用 angularjs 获取隐藏输入的值?

javascript - 如何在动态生成的 input-angularjs 中显示动态 Json 数据?

angularjs - Angular ng-click 事件委托(delegate)

angularjs - 如何使用 Angular 参数指定框架对象的位置?