将 javascript 变量传递给 angularjs 范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19776165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:45:23  来源:igfitidea点击:

Pass javascript variable to angularjs scope

javascriptangularjsflask

提问by Alex

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.

我正在使用烧瓶来呈现一个 html 模板。我想将通过flask 的render_template 传递的变量add_html_data 传递给AngularJs 控制器范围。

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 {[{}]}).

在这种情况下,{{}} 表示烧瓶变量(我将 angularjs 绑定语法更改为 {[{}]})。

Also, I tried creating an intermediary javascript variable

另外,我尝试创建一个中间 javascript 变量

<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

感谢您的帮助

回答by Miguel

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

您可以init()在控制器中创建一个函数:

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>

回答by reptilicus

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 $httprequest to put that on the controller's scope, thats the angular way to do things. Something like this:

我认为@Miguel 的答案可能有效,但我只会创建一个安静的调用来返回定义为 的 JSON 数据块add_html_metadata,并使用$http请求将其放在控制器的范围内,这就是做事的角度方式。像这样的东西:

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

回答by Maxim Shoustin

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

我没有烧瓶的经验,无论如何,尝试使用ng-include