Reputation: 217
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>
Upvotes: 0
Views: 795
Reputation: 411
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
Upvotes: 1