【问题标题】:How to Bind Data Of angular-Charts Dynamically如何动态绑定角图数据
【发布时间】:2015-01-06 04:28:36
【问题描述】:

我在我的应用程序中使用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
  });
};

这很好用,这就是输出。

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

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

这是输出:

控制台上也没有错误。

【问题讨论】:

  • 尝试添加 if(!$scope.$$phase) $scope.$apply();
  • 显示你的 ajax 代码。它应该使用 $http 或 $resource
  • @pankajparkar 不,我只是使用文件选择器从 json 文件中获取数据
  • 你是如何获取这些数据的?
  • @pankajparkar 我已经修改了这个问题,包括我读取 json 文件的代码

标签: javascript json angularjs charts angularjs-controller


【解决方案1】:

你的问题解决方法很简单。

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

代码

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

我为测试创建了一个 test.txt 文件,并在其中编写了以下代码。

test.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 了解更多信息。 希望这对您很有帮助。

【讨论】:

  • 它在提琴手中工作,不适用于我的项目。是否有必要解析成 Json,因为我已经有 Json 文件
  • 是的..因为该指令以字符串格式返回数据。无论如何您需要解析它以获取实际的 JSON
  • 在小提琴中我使用了 $scpe.data 你应该用 $scope.widget.data 替换它
【解决方案2】:

尝试添加 $scope.$apply();在 $scope.widget.data = $fileContent;

之后

【讨论】:

    猜你喜欢
    • 2014-02-23
    • 1970-01-01
    • 2020-03-08
    • 1970-01-01
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多