Integrate AngularJS with Django¶
XMLHttpRequest¶
As a convention in web applications, Ajax requests shall send the HTTP-Header:
X-Requested-With: XMLHttpRequest
while invoking POST-requests. In AngularJS versions 1.0.x this was the default behavior, but in versions 1.1.x this support has been dropped. Strictly speaking, Django applications do not require this header, but if it is missing, all invocations to:
request.is_ajax()
would return False
, even for perfectly valid Ajax requests. Thus, if you use AngularJS version
1.1.x or later, add the following statement during module instantiation:
var my_app = angular.module('MyApp').config(function($httpProvider) {
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
});
Bound Forms¶
AngularJS’s does not consider bound forms, rather in their mindset data models shall be bound to the form’s input fields by a controller function. This, for Django developers may be unfamiliar with their way of thinking. Hence, if bound forms shall be rendered by Django, the behavior of AngularJS on forms must be adopted using a special directive which overrides the built-in form directive.
To override the built-in behavior, refer to the Javascript file django-angular.js
somewhere on
your page
<script src="{% static 'djng/js/django-angular.min.js' %}" type="text/javascript"></script>
and add the module dependency to your application initialization
var my_app = angular.module('myApp', [/* other dependencies */, 'djng.forms']);