Orelus Orelus - 7 months ago 44
AngularJS Question

Error Angular.js with Flask

I have the following structure and code :



<!doctype html>
<html ng-app="myApp">
<meta charset="utf-8"/>
<title>My App</title>
<body ng-controller="myCtrl as ctrl">
<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;

and app.py

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

def hello_world():
return render_template('index.html')

if __name__ == '__main__':

Whatever I do, I still have the following error :
UndefinedError: 'ctrl' is undefined
which I guess is due to the fact that Flask does not load the angular.js

I also tried with the static path

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

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

But still no sucess... Any ideas ?


When you put


in your template, Jinja looks for a context variable named ctrl. Your hello_world endpoint doesn't provide any such variable.

If you would like ctrl to be processed by Angular instead of by Jinja, you need to tell Jinja to include the 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 want all of the curly braces, you have a couple of other options.

You can use Jinja's raw and endraw directives to output its contents exactly as provided.

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

The other option is to change the symbols Angular looks for.

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

app.config(['$interpolateProvider', function($interpolateProvider) {

This would allow you to use