最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Pass javascript variable to angularjs scope - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question edited Nov 4, 2013 at 20:18 Alex asked Nov 4, 2013 at 20:08 AlexAlex 19.2k9 gold badges64 silver badges81 bronze badges 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. – charlietfl Commented Nov 4, 2013 at 20:21
Add a ment  | 

3 Answers 3

Reset to default 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>

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

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

发布评论

评论列表(0)

  1. 暂无评论