0

wowee....can't use flask to return a json object to plot a flot chart in angularjs.

Totally does not work. I use the hard coded json...the chart shows. Whats the deal with a get requests in angularjs? I go to localhost:5000/datatest and I see my json object. Yet angular will not plot a valid json object?

In flask..

@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

My Controller and Directive.

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();
        }
    };
});

My 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 Answer 1

2

Your directive is calling $plot before $http finishes getting data. Instead, you can watch the data array in your directive, and call $plot when it changes:

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>

Here is a demo: http://plnkr.co/7nx2Xf5i1OfLEkzMdwNm

Sign up to request clarification or add additional context in comments.

2 Comments

why was <chart data='data'></chart> used instead of <chart ng-model='data'></chart>
preference. the alternative with ng-model feels less natural to me: plnkr.co/edit/JSD6VWChVFGx9g5baeYj?p=preview

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.