0

I am currently creating a search box which will give suggested list taken from database but I am having trouble getting the correct syntax in passing Python list to AngularJS module.

This is my Python List:

TaskNameList =  [{'id':'1','name':'Alabama'},{'id':'2','name': 'Alaska'}]

I think I wasn't able to get the correct syntax here where the TaskNameList is from views.py:

$scope.states = {{ TaskNameList }};

And this is my complete template codes:

index.html:

<html ng-app="ui.bootstrap.demo">
  <head>
    <script>
      angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('TypeaheadCtrl', function($scope, $http) {

  $scope.selected = undefined;
  $scope.states = {{ TaskNameList }};
  // Any function returning a promise object can be used to load values asynchronously
  $scope.getLocation = function(val) {
    return $http.get('', {
      params: {
        sensor: false
      }
    }).then(function(response){
      return response.data.results.map(function(item){
        return item.formatted_address;
      });
    });
  };

});
    </script>
  </head>
  <body>

<div class='container-fluid' ng-controller="TypeaheadCtrl">

    <h4>Static arrays</h4>
    <input type="text" ng-model="selected" typeahead="state as state.name for state in states | filter:{name:$viewValue} | limitTo:8" class="form-control">

   </div>
  </body>
</html>
1
  • Django varibles in javascript access as "{{ TaskNameList }}". Can you show console.log("{{ TaskNameList }}") ? Commented Sep 1, 2015 at 8:59

1 Answer 1

1

A better option is to convert the array to json, like so:

import json
TaskNameListJson = json.dumps(TaskNameList)

and in your template (using safe filter for HTML escaping):

{{ TaskNameListJson|safe }}

BTW, you should use the verbatim tags, to avoid conflicts with angular templating syntax: https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#verbatim

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

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.