I would start out by organizing the Flask app in the standard structure as follows:
app
|-- app.py
|-- static
|-- css
|-- img
|-- js
|-- templates
And as btford mentioned, if you are doing an Angular app, you'll want to focus on using Angular client-side templates and stay away from server-side templates. Using render_template('index.html') will cause Flask to interpret your angular templates as jinja templates, so they won't render correctly. Instead, you'll want to do the following:
@app.route("/")
def index():
return send_file('templates/index.html')
Note that using send_file() means that the files will be cached, so you might want to use make_response() instead, at least for development:
return make_response(open('templates/index.html').read())
Afterwards, build out the AngularJS part of your app, modifying the app structure so that it looks like this:
app
|-- app.py
|-- static
|-- css
|-- img
|-- js
|-- app.js, controllers.js, etc.
|-- lib
|-- angular
|-- angular.js, etc.
|-- partials
|-- templates
|-- index.html
Make sure your index.html includes AngularJS, as well as any other files:
<script src="static/lib/angular/angular.js"></script>
At this point, you haven't yet constructed your RESTful API, so you can have your js controllers return predefined sample data (only a temporary setup). When you're ready, implement the RESTful API and hook it up to your angular app with angular-resource.js.
EDIT: I put together an app template that, though a little more complex that what I've described above, illustrates how one could build an app with AngularJS + Flask, complete with communication between AngularJS and a simple Flask API. Here it is if you want to check it out: https://github.com/rxl/angular-flask
After some diving through some documentation and source code, I think I got it working. Perhaps this will be useful for someone else?
I added the following to my module configuration:
angular.module(...)
.config( ['$routeProvider', function($routeProvider) {...}] )
.run( function($rootScope, $location) {
// register listener to watch route changes
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
if ( $rootScope.loggedUser == null ) {
// no logged user, we should be going to #login
if ( next.templateUrl != "partials/login.html" ) {
// not going to #login, we should redirect now
$location.path( "/login" );
}
}
});
})
The one thing that seems odd is that I had to test the partial name (login.html
) because the "next" Route object did not have a url or something else. Maybe there's a better way?
Best Answer
If you're using
ng-view
in your Angular app you can listen for the$viewContentLoaded
event and push a tracking event to Google Analytics.Assuming you've set up your tracking code in your main index.html file with a name of
var _gaq
and MyCtrl is what you've defined in theng-controller
directive.UPDATE: for new version of google-analytics use this one