Flot,angularjs和获取数据通过http get绘制

时间:2014-04-19 13:57:22

标签: json angularjs flask

wowee ....不能使用flask来返回一个json对象来绘制angularjs中的flot图表。

完全不起作用。我使用硬编码的json ...图表显示。什么是与angularjs的get请求交易?我去localhost:5000 / datatest,我看到了我的json对象。然而angular不会绘制有效的json对象吗?

在烧瓶中..

@app.route('/datatest')
def datatest():
    test1 = [[[0, 1], [1, 5], [2, 2]]]
    data = json.dumps(test1)
    resp = Response(data, status=200, mimetype='application/json')
    return resp

我的控制器和指令。

var App = angular.module('App', []);

App.controller('Ctrl', function ($scope,$http) {

     $http.get('datatest').success(function(data) {
        $scope.data = data;
    });


    //$scope.data = [[[0, 1], [1, 5], [2, 2]]];

});


App.directive('chart', function() {
    return {
        restrict: 'E',
        link: function(scope, elem, attrs) {
            var data = scope[attrs.ngModel];
            $.plot(elem, data, {});
            elem.show();
        }
    };
});

我的HTML:

<!DOCTYPE html>
<html>
  <head>

    <script type="text/javascript" src="static/js/jquery/jquery-2.1.0.js"></script>
    <script type="text/javascript" src="static/js/flot/jquery.flot.js"></script>
    <script type="text/javascript" src="static/js/angular/angular.min.js"></script>
    <script type="text/javascript" src="static/lib/flot/controller.js"></script>
    <style type='text/css'>
       chart {
            display:none;
            width:400px;
            height:200px;
        }
   </style>
 </head>
 <body>
    <div ng-app='App'>
        <div ng-controller='Ctrl'>
            <chart ng-model='data'></chart>
        </div>
    </div>    
  </body>
</html>

1 个答案:

答案 0 :(得分:2)

您的指令在$plot完成$http之前调用data。相反,您可以在指令中查看data数组,并在更改时调用$plot

app.directive('chart', function() {
  return {
    restrict: 'E',
    scope: {
      data: '='
    },
    link: function(scope, elem, attrs) {
      scope.$watch('data', function() {
        if (scope.data.length > 0) {
          $.plot(elem, scope.data, {});
          elem.show();
        }
      })
    }
  };
});

html:<chart data='data'></chart>

以下是演示:http://plnkr.co/7nx2Xf5i1OfLEkzMdwNm