AngularJS directives don't seem to work with Python Flask

Viewed 377

Even though my issue might be a common one, I couldn't find a clear answer for it. I'm a beginner with AngularJS and there is a very simple code that is not working, and actually all my directives doesn't work. Here is my small project

/templates
    -index.html
    -header.html
    -script.js
mainapp.py

In index.html there is

<!DOCTYPE html>
<html data-ng-app>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>
    <div data-ng-include="'header.html'"></div>
</body>
</html>

in header.html

<div> I'm supposed to see this </div>

And mainapp.py

from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def mainpage():
    return render_template("index.html")

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

Nothing in script.js

When I'm running mainapp.py I'm expecting to see "I'm supposed to see this" but I don't because the directives doesn't seem to be working. However if I'm trying the html code alone (on Plunker for example) it's working fine.

I assume there is configuration that I need to do but I have no idea what, any ideas? (and if someone could provide an explanation for why it's not working that would be great)

Note that using data- before my directives doesn't change the issue.

Thanks

1 Answers

The issue has to do with how Flask handles static files vs. templates. The header.html file is really a static file in your situation, not a Flask template.

Change your directory structure to:

├── mainapp.py
├── static
│   └── partials
│       └── header.html
└── templates
    └── index.html

Then update the ng-include to:

<div data-ng-include="'header.html'"></div>

If this were me, I wouldn't even use a "templates" directory. Just serve up a your index.html file from the static directory so that when an end user hits the main / route, Angular takes over. Then, you can just interact with the server-side via making AJAX requests against the RESTful API.

Related