2

I want to add simple angularjs code to django. For this I have taken the simple example: I have put the below code in my template:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function($scope) {
        $scope.firstName = "John";
                $scope.lastName = "Doe";
        });
</script>

<div ng-app="myApp" ng-controller="myCtrl">

        First Name: <input type="text" ng-model="firstName"><br>
        Last Name: <input type="text" ng-model="lastName"><br>
<br>
        Full name:{{firstName}}

</div>
</body>
</html>

My view.py is as follows:

from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader

# Create your views here.
def index(request):
        template = loader.get_template('warlist/index.html')
        return HttpResponse(template.render())

Now when I run it,it is taking the names in the text feild but It is not printing the full name. However same angularjs code is working fine without django.

2 Answers 2

2

That's because you are using Django template engine to render firstName. But it is not passed through your view and, thus, it's not recognized by Angular. To "escape" {{ }} characters and use Angular's, do this:

Full name: {% verbatim %}{{firstName}}{% endverbatim %}

That way Django will not try to parse {{ }} and instead Angular's {{ }} will be used. Check verbatim for details.

Sign up to request clarification or add additional context in comments.

2 Comments

Great man..It is working.How to transfer the value of the firstName and lastName in views.py. Any clue?I want to parse the text that user has entered in the text section.
For that, it is better to ask a different question. That's how SO works. No sub-questions in comments. However, in a nutshell, you would create a form (which will include the <input> tags) and make a POST request to Django. Your view then will receive the values of the <input>s and handle them approprietly.
2

Django templates use the same interpolation than angular, which is double brackets {{}}. You can use $interpolateProvider in your config method to change angular notation, so it doesn't collide with Django templates.

module
  .('myApp')
  .config(function($interpolateProvider) {
    $interpolateProvider.startSymbol('{$');
    $interpolateProvider.endSymbol('$}');
})

Then anytime you need to interpolate anything in your view:

Fullname: {$ firstName + lastName $}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.