AngularJS: useful tips to get started

AJAX POST calls: CSRF token for Django

In order to pass in the required CRSF token for Django POST requests, we can config our Angular module to add the X-CSRFToken POST header parameter on every call. To do so, set a config on the app module that way:

var myApp = angular.module('myApp').config(function($httpProvider) {
    $httpProvider.defaults.headers.post['X-CSRFToken'] = $('input[name=csrfmiddlewaretoken]').val();
});

In this scenario, the csrfmiddlewaretoken is output by the Django template context as an hidden input field.

Download gist: ANGULARJS - Django CSRF Token header setup

Route path changes (or URL redirect)

Obviously in AngularJS, we don't actually redirect the user but we change the url path (the one followed by #/) in order to load a different controller. It is quite simple to do, simply by giving a url parameter to the path() method:

myApp.controller('myCtrl',function myCtrl($location){
    $location.path('/mypath')
}

Do not forget to pass $location in your controller arguments!

More in depth documentation is available on the AngularJS $location reference page

Passing data to a POST call with $http

The $http POST call on AngularJS will not automatically convert your data array to a set of parameter for the AJAX call. So you must encode the data array as follow (i'm using jQuery to do so):

$.param(data))

$scope.add_flight_route = function(){
    var d = new Date();
    var data = {route_id:$rootScope.route_info.route_id}
    $http.post('/ajax/vall/?rand='+d.getTime(), $.param(data)).success(function(data) {
        // do things...
    });
}

Related links

http://deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UPDATED

< / >