将Python列表传递给AngularJS模块

时间:2021-03-05 18:07:54

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.

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

This is my Python List:

这是我的Python列表:

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:

我想我无法在这里得到正确的语法,其中TaskNameList来自views.py:

$scope.states = {{ TaskNameList }};

And this is my complete template codes:

这是我完整的模板代码:

index.html:

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 个解决方案

#1


1  

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

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

import json
TaskNameListJson = json.dumps(TaskNameList)

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

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

{{ 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

顺便说一下,你应该使用verbatim标签,以避免与角度模板语法冲突:https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#verbatim

#1


1  

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

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

import json
TaskNameListJson = json.dumps(TaskNameList)

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

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

{{ 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

顺便说一下,你应该使用verbatim标签,以避免与角度模板语法冲突:https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#verbatim