1

I am using flask to render an html template. I would like to pass variable add_html_data, that I pass through flask's render_template, to an AngularJs controllers scope.

I tried

<body>
    <div ng-controller="layoutController" ng-init="entries= {{ add_html_metadata|tojson }}"/>
</body>

In this case {{}} represent flask variables (I changed angularjs binding syntax to {[{}]}).

Also, I tried creating an intermediary javascript variable

<script type="text/javascript">var entries = {{ add_html_metadata|tojson }}</script>

But, still cannot figure out how to attach it to the controllers scope.

Thanks for any assistance

1
  • You now have a global variable entries. Since global variables are available anywhere in js code.... inside an angular controller or directive or service $scope.entries=entries. Commented Nov 4, 2013 at 20:21

3 Answers 3

2

You can create an init() function in your controller:

app.controller('layoutController', function($scope) {
    $scope.init = function(html_metadata) {
        $scope.html_metadata = html_metadata;
    }
});

Then in your template you can invoke this function with the data:

<body>
    <div ng-controller="layoutController" ng-init="init({{ add_html_metadata|tojson }})"/>
</body>
Sign up to request clarification or add additional context in comments.

Comments

1

I think @Miguel's answer may work, but I would just create a restful call to return the JSON blob of data defined as add_html_metadata, and use a $http request to put that on the controller's scope, thats the angular way to do things. Something like this:

@app.route("/html_metadata", methods=["GET"])
def get_html_metadata():
   #do something in here
   return jsonify(html_metadata)

And in the angular controller

myApp.controller('layoutController', ['$scope', function($scope) {

  $http({method: 'GET', url: '/html_metadata'}).
    success(function(data, status, headers, config) {
      $scope.html_metadata = data
   }); 
}]);

Comments

0

I have no experience with flask, anyways, Try to use ng-include

Comments

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.