Reputation: 689
I have a list of items, each one with a checkbox. The user selects some of items, and then he may search for other items by typing a query, and then pressing "Search" button which do a POST. I don't want to lose the previous selected items. So in my views, I get the checked items ids which are stored in the checkbxes values, and then re-send them to the template. The problem is that I am using ng-repeat and not {% for %} to create the items' list because I am doing some filtering tasks with angularJS, so I am not able to know if the current item's id exists in the checked ids list which is passed to the template after the POST or not.
Views code:
if 'btn_search' in request.POST:
checked_ids = get_integers_from_checked_checkboxes(request, 'checkbox_parent')
search_query = request.POST['txtbox_search']
sub_queries = search_query.split(' ')
for sub_query in sub_queries:
items= all_items.filter(items__name__contains=sub_query)
return render_to_response('my_page.html',
{'items': items,
'checked_items' : checked_ids},
context_instance=RequestContext(request))
A simplified Template code:
<!-- Search -->
<input type="text" name="txtbox_search">
<button name="btn_search"><b>Search</b></button>
<!-- Items' list -->
<input type="text" ng-model="filter_Search_box" placeholder="Filter search">
<ul class="list">
<li ng-repeat="item in items | filter:filter_Search_box">
<!-- This check box should be checked if the item.id is in {{checked_items}} -->
<input type="checkbox" value="{/item.id/}" name="checkbox_item"/>
<b>{/item.name/} </b>
</li>
Upvotes: 1
Views: 348
Reputation: 1379
You should consider using ajax communication between your angular and django apps. So your django view would return json object which would be loaded dynamically by your angular app. Also you could achieve it in a dirty way:
views.py
from django.core import serializers
if 'btn_search' in request.POST:
checked_ids = get_integers_from_checked_checkboxes(request, 'checkbox_parent')
search_query = request.POST['txtbox_search']
sub_queries = search_query.split(' ')
for sub_query in sub_queries:
items = all_items.filter(items__name__contains=sub_query)
items = serializers.serialize('json', items)
return render_to_response('my_page.html',
{
'items': items,
'checked_items': checked_ids
},
context_instance=RequestContext(request))
file_.html:
<script>
window.items = eval('(' + '{{ items }}' + ')');
</script>
in your angular controller initialize:
$scope.ang_items = window.items;
Then you will be able to make ng-repeat out of ang_items. But I HIGHLY DON'T RECOMMEND THIS SOLUTION.
Also your for loop (for sub_query in sub_queries:
) overwrite items with every iteration, that's probably not desirable thing. I would RECOMMEND getting familiar with this.
Upvotes: 1