将Python列表传递给AngularJS模块

时间:2015-09-01 08:54:02

标签: python angularjs django module

我目前正在创建一个搜索框,该搜索框将提供从数据库中获取的建议列表,但在将Python列表传递给AngularJS模块时,我无法获得正确的语法。

这是我的Python列表:

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

我认为我无法在这里获得正确的语法,其中TaskNameList来自views.py

$scope.states = {{ TaskNameList }};

这是我完整的模板代码:

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 个答案:

答案 0 :(得分:1)

更好的选择是将数组转换为json,如下所示:

import json
TaskNameListJson = json.dumps(TaskNameList)

并在您的模板中(使用安全过滤器进行HTML转义):

{{ TaskNameListJson|safe }}
顺便说一下,您应该使用逐字标记,以避免与角度模板语法发生冲突:https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#verbatim