Angular.js error with flask

I have the following structure and code:

project/
       app.py
       templates/
                /index.html
       static/
             /angular.js

      

index.html

<!doctype html>
<html ng-app="myApp">
<head>
    <meta charset="utf-8"/>
    <title>My App</title>
</head>
<body ng-controller="myCtrl as ctrl">
    <div>
        {{ctrl.foo}}
    </div>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js"></script>
    <script type="text/javascript">

        angular.module('myApp', [])
        .controller('myCtrl', [function () {
            var self = this;
            self.foo = 10;
        }]);
    </script>
</body>
</html>

      

and app.py

from flask import Flask
app = Flask(__name__)
from flask import render_template

@app.route('/')
def hello_world():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)

      

Whatever I do, I still have the following error: UndefinedError: 'ctrl' is undefined

which I think is due to Flask not loading angular.js

I have also tried the static path

<script type=text/javascript src="{{url_for('static', filename='angular.js')}}"></script>

and <script type=text/javascript src="../static/angular.js"></script>

But so far no success ... Any ideas?

+3


source to share


1 answer


When you place

{{ctrl.foo}}

      

in your template, Jinja looks for a context variable named ctrl

. The endpoint hello_world

does not provide such a variable.

If you want to ctrl

be rendered by Angular and not Jinja, you need to tell Jinja to include curly braces in the rendered HTML. This can be done by surrounding what you have in additional curly braces .

{{ '{{ctrl.foo}}' }}

      

If you don't need all the curly braces, you have a few other options.



You can use Jinja directives raw

and endraw

to display its contents exactly as directed.

{% raw %} {{ctrl.foo}} {% endraw %}

      

Another option is to change the symbols Angular is looking for .

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

app.config(['$interpolateProvider', function($interpolateProvider) {
  $interpolateProvider.startSymbol('[[');
  $interpolateProvider.endSymbol(']]');
}]);

      

This will allow you to use

[[ctrl.foo]]

      

+7


source







All Articles