How to add data from html to Database using AngularJS? - javascript

am using AngularJS/Django/Python for my project. One of my page taking inputs from the users through input fields and radio buttons and need to store those values to the database. How can I do that by using AngularJS? Thanks in advance.
html and JS:
{% extends "base.html" %}
{% load static %}
{% block stylesheets %}
<!--<html ng-app="ui.bootstrap.demo">-->
<link href="{% static 'bootstrap-v3.3.2/css/bootstrap.min.css' %}" rel="stylesheet" xmlns="http://www.w3.org/1999/html">
<link href="{% static 'bootstrap-v3.3.2/css/bootstrap-theme.min.css' %}" rel="stylesheet">
<link href="{% static 'css/screen.css' %}" rel="stylesheet">
<link href="{% static 'css/project.css' %}" rel="stylesheet">
<link href="{% static 'css/jquery-ui.css' %}" rel="stylesheet">
<link href="{% static 'css/ss.css' %}" rel="stylesheet">
<link href="{% static 'css/check_binning.css' %}" rel="stylesheet">
{% endblock %}
{% block mainbody %}
{% include 'orc_navigation_section.html' %}
<br><br>
<h1> <b>Check Binning Setup</b></h1><br>
<div class="well">
<div class="well" ng-controller="LayerCtrl">
<table>
<tr>
<td>
<div class="input-group">
<span class="input-group-addon">Fab</span>
<select class="form-control" name="fab">
{% for f in fab %}
<option value="{{f}}">{{f}}</option>
{% endfor %}
</select>
</div>
</td>
<td>
<div class="input-group">
<span class="input-group-addon">Technode</span>
<select class="form-control" ng-model="selected_technode" ng-options="l.value as l.label for l in technodes"></select>
</div>
</td>
<td>
<div class="input-group">
<span class="input-group-addon">Layer</span>
<!--<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">-->
{%verbatim%}
<!--<select class="form-control" name="layer" >-->
<!--<option ng-repeat="l in layer_list" value="{{l}}">{{l}}</option>-->
<!--</select>-->
<select class="form-control" ng-model="selected_layer" ng-options="l as l for l in layerlist"></select>
{%endverbatim%}
</div>
</td>
</tr>
</table>
</div>
<div><h3>ORC binning setup history:</h3></div>
<br/><br/>
<!--Check fields and Radio Buttons-->
<div ng-controller="AlertDemoCtrl">
<table class="table">
{% verbatim %}
<tr>
<td class="input-group" ng-repeat="(k,v) in alerts">
<span class="input-group-addon" ng-hide="v.hide">Check {{ k }}</span>
<span ng-hide="v.hide">
<input type="text" class="form-control" placeholder="Add Check here" ng-model="v.input">
<b>Functional check</b> <input type="radio" name="{{ k }}" value="fc" ng-model="v.props">
<b>CFM issue</b> <input type="radio" name="{{ k }}" value="cfm" ng-model="v.props">
<b>Defect risk</b> <input type="radio" name="{{ k }}" value="dr" ng-model="v.props">
<a type="reset" ng-click="reset()">
<span class="glyphicon glyphicon-repeat"></span>
</a>
<a href="" ng-click="remove(v)">
<span class="glyphicon glyphicon-trash"></span></a>
</span>
{% endverbatim %}
<tr>
<td>
<button type="button" class='btn btn-info' ng-click="addAlert()">
<span class="glyphicon glyphicon-plus"></span>
Add Check</button>
<button type="reset" ng-click="reset()" class="btn btn-danger">
<span class="glyphicon glyphicon-repeat"></span>
Reset All</button>
</td>
</tr>
</table>
</div>
<table class="table">
<!--IMPORT FILE-->
<tr>
<td>
<div style="position:relative;">
<a class='btn btn-primary' href='javascript:;' disabled>
Choose File...
<input type="file" style='position:absolute;z-index:2;top:0;left:0;
filter: alpha(opacity=0);-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
opacity:0;background-color:transparent;color:transparent;' name="file_source" size="40" onchange='$("#upload-file-info").html($(this).val());'>
</a>
<span class='label label-info' id="upload-file-info"></span>
<button ng-click="uploadAttachFile()" class="btn btn-small btn-default" id="uploadfile" name="uploadfile" disabled>
<span class="glyphicon glyphicon-cloud-upload"></span> Import File</button>
</div>
</td>
</tr>
<!--ADD COMMENTS-->
<tr>
<td>
Add Comments*<div class="span5"><textarea name="bugnote_text" placeholder="Add comments here (max=600 characters)" rows="3" class="span10 ng-pristine
ng-valid ng-valid-maxlength" ng-maxlength="600"></textarea></div>
</td>
<td>
Add ECN*<input type="text" class="form-control" placeholder="Add ECN here">
</td>
</tr>
<form ng-submit="submit()" ng-controller="ExampleController">
<tr>
<td>
<button type="submit" id="submit" class="btn btn-small btn-success"><span class="glyphicon glyphicon-pencil"></span> Update check DB</button>
<button class="btn btn-small btn-grey"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
</td>
</tr>
</form>
<!--<tr><td><div ng-controller="ModalDemoCtrl">-->
<!--<script type="text/ng-template" id="orc_enable.html">-->
<!--</script>-->
<!--<button type="button" class="btn btn-default" ng-click="open('lg')">Pop-up</button>-->
<!--</div></td></tr>-->
</table>
</div>
<script>
angular.module('submitExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function() {
if ($scope.text) {
$scope.list.push(this.text);
$scope.text = '';
}
};
}]);
</script>
{% endblock %}
The .js file:
{% block extrascript %}
{{ ngapp }}.controller("LayerCtrl", function ($scope, $http, $resource){
var layerresource_url = $resource("{% url 'api_dispatch_list' 'v1' 'layer' %}");
$scope.technodes = [
{'value': 22, 'label': 22},
{'value': 28, 'label': 28},
];
console.log('initializing....')
$scope.$watch('selected_technode', function () {
<!--alert($scope.selected_technode);-->
$scope.update_layer();
});
$scope.update_layer = function(){
console.log('Stage1: Initializing Primary Data... ');
layerresource_url.get({techtype__contains: $scope.selected_technode, limit:1500},
function(data){
$scope.layerlist = data['objects'][0]['layer'];
console.log($scope.layerlist);
},function(data, status){
console.log('Stage1: Internal error while loading initial data:'+status );
alert('internal error');
}
);
};
});
{{ ngapp }}.controller("AlertDemoCtrl", function ($scope, $http, $resource){
$scope.alerts = [];
$scope.addAlert = function() {
$scope.alerts.push({msg: 'Another alert!', props : 0, input : ""});
};
$scope.closeAlert = function(index) {
$scope.alerts.splice(index, 1);
};
$scope.reset = function() {
angular.forEach($scope.alerts, function(v){
v.input = "";
v.props = 0;
});
};
$scope.remove = function(v){
v.hide = 1;
}
$scope.reset();
});
{% endblock %}
and my view.py
class CheckBinningView(JSONResponseMixin, ListView):
template_name = "orc_enable.html"
model = OrcRecord
def get_context_data(self, *args, **kwargs):
context = super(CheckBinningView, self).get_context_data(*args, **kwargs)
fab = GroupProfile.objects.get(id=self.request.session['ACL_gid']).fab
gp = GroupProfile.objects.get(id=self.request.session['ACL_gid'])
layer = []
technode = []
for l in self.model.objects.raw('SELECT distinct layer, id FROM orc_orcrecord GROUP BY layer'):
layer.append(l.layer)
if fab == "ALL":
SQL = "SELECT distinct process_id, id FROM orc_orcrecord GROUP BY process_id"
else:
SQL = "SELECT distinct process_id, id FROM orc_orcrecord \
WHERE process_id LIKE '0" + fab +"%%' or process_id LIKE '" + fab + "%%' GROUP BY process_id"
print SQL
for t in self.model.objects.raw(SQL):
sql = "SELECT distinct process_id, id FROM orc_orcrecord GROUP BY process_id"
else:
sql = "SELECT distinct process_id, id FROM orc_orcrecord \
WHERE process_id LIKE '0" + fab +"%%' or process_id LIKE '" + fab + "%%' GROUP BY process_id"
print sql
for t in self.model.objects.raw(sql):
try:
technode.append(t.get_technode)
except Exception, e:
print e
continue
# for t in self.model.objects.filter(process_id__startswith=fab, is_main_record=True,
# mantis_id__isnull=False).values_list('id', flat=True).order_by('id').distinct()[:100]:
# technode.append(self.model.objects.get(id=t).get_technode)
# context['technode'] = gp.technology
context['fab'] = gp.fab
context['technode'] = list(set(technode))
# context['layer'] = list(set(layer))
context['technode'] = list(set(technode))
context['ngapp'] = "CMOD"
return context

You should look in this link about forms
will give you idea about ng-model. then you go the end points, see this resource api as you are using it.
You can use easily as:
var layerresource_url = $resource("{% url 'api_dispatch_list' 'v1' 'layer' %}");
layerresource_url.field1 = "teste";
layerresource_url.field2 = true;
layerresource_url.field1.$save();
//will make a post to the URL passed in $resource
If you want to some customization:
var layerresource_url = $resource("{% url 'api_dispatch_list' 'v1' 'layer' % ,
{},{ save:{method:'POST'}}
}");
so you can just use like:
layerresource_url.save(model)
please read the link about resources.
you also have to setup the server side to accept the post.

There's a lot of steps here.
Your server (Django) needs to be available to receive the POST from the client.
Your client needs to capture user input. Angular is one way, but by no means the only way. If you're struggling with this, jQuery is far more accessible. If you're going to stick with Angular, look into ng-model like Alvaro mentions.
You need to make the POST. In Angular, you can do this with $resource and $http. Both are well documented. All you want is the vanilla POST, nothing fancy. Make sure the content of your form is in the body of your post.
You may run into Content-Type issues... you'll probably want your ContentType set to application/json; charset=utf-8 if you're working on js.

Related

My button is only clickable once. I'd like to be able to repeat many searches

My problem is opposite to most people. I want to be able to search for a user multiple times. For example, if I look up Ray, I retrieve ray's data. Then if I look up bob, I want to retrieve bob's data.
However, my code works to retrieve the data from the first search. It then appears your clicking the button, but nothing is happening.
I have not tried much, because I don't know where to start.
<div align="center">
</div>
<!--
<div class = "box" style = "width:100%; text-align:center;">
<form method = "POST">
<input style = "float:left;"type="search" class="form-control" type="text" name = "search" placeholder="Enter First and Last name to begin" aria-label="Search" > </input>
<button style = "float:right;"type="submit" class="btn btn-success" id ="search" onclick="fetchlist();return false;">Search</button>
</form>
-->
<div style="text-align: center;">
{% from "_formhelpers.html" import render_field %}
<form method="POST" action="/">
<dl style="display: inline-block; text:white;" >{{render_field(form.search)}} </dl>
<button id="searchbutton" type="submit" style="display: inline-block;" class="btn btn-outline-success my-2 my-sm-0" onclick="fetchlist(); return false;">Search</button>
<br>
{% if error %}
<p class = "error"><strong>Error:</strong>{{error}}</p>
{% endif %}
</form>
</div>
{% if data %}
<div style="text-align:center;">
<table id="list" style="display:none;" class = "table table-hover" >
<thead>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Rating</th>
<th scope="col">Review</th>
</thead>
<tbody>
{% for row in data %}
<tr>
{% for d in row %}
<td>{{ d }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}
</body>
<script>
function fetchlist() {
if (document.getElementById('searchbutton').onclick) {
document.getElementById('list').style.display = 'inline';
}
else document.getElementById('list').style.display = 'inline';
}
</script>
{% endblock %}
#app.route('/', methods=['GET', 'POST'])
def homepage():
try:
form=SearchForm(request.form)
global d1
d1 =""
if request.method == "POST":
s1 = form.search.data
a = s1.split(" ",1)
firstname, lastname = (a[0], a[1])
c,conn = connection()
qry = "SELECT FirstName, LastName FROM posts WHERE FirstName LIKE (%s) AND LastName like (%s)"
c.execute(qry, ((thwart(firstname)), (thwart(lastname))))
d1 = c.fetchall()
c.close()
conn.close()
print(d1)
else: print('error')
return render_template("index.html", data=d1, form = form)
except Exception as e:
return(str(e))
No error messages. I expect to perform multiple searches.

pass value to bootstrap modal form with django

When I use bootstrap modal for my form its only show first value.
here my template.html
{% for company in companys %}
<tr>
<td>{{ company.name }}</td>
<td>{{ company.desc }}</td>
<td align="center">
<button type="button" class="btn btn-warning margin-bottom" data-toggle="modal" data-target="#modal-default2">
delete
</button>
<div class="modal fade" id="modal-default2">
<div class="modal-dialog">
<form method="post" action="{% url 'system:company_delete' pk=company.pk %}">
{% csrf_token %}
<div class="modal-content">
<div class="modal-body">
<input type="text" name="name" maxlength="100" required="" id="id_name" value="{{ company.pk }}">
<input type="submit" class="btn btn-primary" value="Delete">
</div>
</div>
</form>
</div>
</div>
</td>
</tr>
{% endfor %}
its loop all the data, when click delete confirm form will popup. but its return same value.
but if without modal-bootstrap its work fine.
example: template.html
{% for company in companys %}
<tr>
<td>{{ company.name }}</td>
<td>{{ company.desc }}</td>
<td align="center">
<form method="post" action="{% url 'system:company_delete' pk=company.pk %}">
{% csrf_token %}
<input type="text" name="name" maxlength="100" required="" id="id_name" value="{{ company.pk }}">
<input type="submit" class="btn btn-primary" value="Delete">
</form>
</td>
</tr>
{% endfor %}
it's work fine.
what I should do to make it work?...
update
views.py
# Company Crud
class CompanyListView(ListView):
context_object_name = 'companys'
model = models.Company
class CompanyCreateView(CreateView):
fields = ('name', 'desc')
model = models.Company
class CompanyUpdateView(UpdateView):
fields = ('name', 'desc')
model = models.Company
class CompanyDeleteView(DeleteView):
model = models.Company
success_url = reverse_lazy("system:company_list")
Your ajax modal will always return the same value inside modal because:
- Modal has this data-target="#modal-default2" as the target, however, your loop contains the modal body, with the id id="modal-default2", which will render modal as much as your loop goes.
So what you can do is to define a unique ID for each modal with the ID of each company modal-default{{company.id}}:
{% for company in companys %}
''' rest of codes '''
<button type="button" class="btn btn-warning margin-bottom" data-toggle="modal" data-target="#modal-default{{company.id}}">
delete
</button>
''' rest of codes '''
<div class="modal fade" id="modal-default{{company.id}}">
<div class="modal-dialog">
</div>
</div>
''' rest of codes '''
{% endfor %}
But this method is not effective if you have a lot of data, it will render lots of html codes.
Another option
With AJAX and one modal.
Your html would be:
{% for company in companys %}
<td>{{ company.name }}</td>
<td>{{ company.desc }}</td>
<button data-id="{{company.id}}" type="button" class="btn btn-warning margin-bottom delete-company" >
delete
</button> <!-- be aware of class 'delete-company' -->
{% endfor %}
{% csrf_token %}
<div class="modal fade" id="modal-default">
<div class="modal-dialog">
{% if company %} <!-- this company instance will come from AJAX -->
<form method="post" action="{% url 'system:company_delete' pk=company.pk %}">
{% csrf_token %}
<div class="modal-content">
<div class="modal-body">
<input type="text" name="name" maxlength="100" required="" id="id_name" value="{{ company.pk }}">
<input type="submit" class="btn btn-primary" value="Delete">
</div>
</div>
</form>
{% endif %}
</div>
</div>
AJAX
$(document).on('click','.delete-company',function(){
var id = $(this).data('id');
$.ajax({
url:'',
type:'POST',
data:{
'id':id,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(),
},
success:function(data){
$('#modal-default .modal-dialog').html($('#modal-default .modal-dialog',data));
$('#modal-default').modal('show');
},
error:function(){
console.log('error')
},
});
});
And your views would be:
change your url from CompanyListView.as_view() to companyListView
def companyListView(request):
context = {}
companys = models.Company.objects.all()
if request.method == 'POST' and request.is_ajax():
ID = request.POST.get('id')
company = companys.get(id=ID) # So we send the company instance
context['company'] = company
context['companys'] = companys
return render(request,'template.html',context)

getting a div id using javascript in a foreach loop

I am using laravel and want to make an ajax call to retrieve the id of the product but as u can see here it will get only the first product id because they will have the same id (or the first when the page load)
but i want it to : when i press add to cart, the clicked product id is sent
and my skills are not that good , this is my first app, can any one help ?
here is the code
#foreach($row as $product)
<form method="post" id="reg-form">
<input type="hidden" name="post_id" id="post_id" value="{{ $product->slug }}">
{!! csrf_field() !!}
<div class="col-sm-10 col-lg-3 col-md-10 ">
<div class='productbox '>
#if($image = $product->images()->first())
<img src="{{ $image->thumbnail }} " class="img-responsive" alt="a" />
#endif
<div class="producttitle">{{ $product->name }}</div>
<div class="pull-right">
#for ($i = 5 - $product->rating ; $i < 5 ; $i++)
<a> <i class="price-text-color fa fa-star"></i></a>
#endfor
#for ($i = $product->rating ; $i < 5 ; $i++)
<a> <i class=" fa fa-star"></i></a>
#endfor
</div><br />
<p class="text-justify"></p>
<address class="ellipsis">
<strong>{{ $product->description }}</strong><br>
</address>
<address>
{{ $product->name }}<br>
</address>
<div class="productprice">
<div class="pull-right">
<input type="button" id="getre" class="btn btn-danger btm-sm " role="button" value="Add to Wishlist">
</div>
<div class="pricetext">
<input type="submit" id="getRequest" class="btn btn-info btm-sm " role="button" value="Add to cart">
More Details <span class="glyphicon glyphicon-zoom-in"></span>
<!-- Edit <span class="glyphicon glyphicon-cog"></span> -->
</div>
</div>
</div>
</div>
</form>
#endforeach
this is the javascript
$(document).ready(function()
{
$(document).on('submit', '#reg-form', function()
{
var data = $("#post_id").val();
$.ajax({
type : 'POST',
url : '{{url("/ajax")}}',
data: {'name':data, '_token': $('input[name=_token]').val()},
success : function(data)
{
$(getRequest).replaceWith('<img id=getRequest width=50 height=40 src= http://www.cuisson.co.uk/templates/cuisson/supersize/slideshow/img/progress.BAK-FOURTH.gif> ');
setTimeout(function() {
$(getRequest).replaceWith(' <input type="submit" id="getRequest" class="btn btn-info btm-sm " role="button" value="Add to cart"> ').hide('blind', {}, 500)
}, 1300);
console.log(data);
}
});
return false;
});
});
You are trying to get an element with id="post_id". There could be a lot of these elements in your page. You need to get the element with id="post_id" that is inside your current form element. You can do it in this way:
var data = $(this).find("#post_id").val();
The model of your product should have a unique ID. So when you iterate over all your products, you should set the id of the div with the same ID of the model. Then you can get it with jquery by $(".your-product-div").attr("id")

How to implement adder input in django forms?

I spent several hours trying to figure out,How to implement Adder input in django.
My probleme is in my template I implemented a javascript script that adds additional fields to a form.
those fields are key/value fields, in my model I created a JSONField.
I wanted to grab data from dynamic fields and store them as key values in my JSONField
forms.py
class MyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
form_fields = kwargs.pop("fields", {})
super(CrontabForm, self).__init__(*args, **kwargs)
for field in form_fields:
field_name = field['name']
field_label = field['label']
field_type = field['type']
self.fields[field_name] = forms.CharField(label=field_label)
print fields.name
class Meta:
model = MyModel
models.py
class MyModel(models.Model):
user = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL'), verbose_name=_('User'))
params = JSONField(_('Url params'))
views.py
class MyView(LoginRequiredMixin, SuccessMessageMixin, CreateView):
model = MyModel
form_class = MyForm
template_name = '/index.html'
success_url = '/success/'
success_message = "The instance was created successfully"
def form_valid(self, form):
form.instance.user = self.request.user
return super(MyView, self).form_valid(form)
my jquery.js:
{% block custom_js %}
{{ block.super }}
<script>
console.log('tesss');
$(document).ready(function () {
// Number of params
var index = 0;
function addParams() {
var tmp_template = $('template').clone();
var paramsDiv = $('#params');
paramsDiv.append(tmp_template.html());
$($('[class$="param-x"]')[index]).attr('name', 'param' + (index + 1));
$($('[class$="value-x"]')[index]).attr('name', 'value' + (index + 1));
index = index + 1;
}
addParams();
$('#addParam').on('click', function(){
addParams();
});
});
</script>
{% endblock %}
index.html:
<div class="col-md-12">
<form action="." method="post">
<div class="col-md-6">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<div class="row">
{{ field.errors }}
<label class="col-md-2 control-label">{{ field.label_tag }}</label>
<div class="col-md-6">
{{ field }}
</div>
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
</div>
{% endfor %}
<div class="text-center">
<div class="pagination">
<i class="btn btn-success waves-input-wrapper waves-effect"
style="color:#fff ;background:#5cb85c">
<input class="waves-button-input" type="submit" value="Add"
style="background-color:rgba(0,0,0,0);"></i>
{% url 'cron:crontab-list' as cronslist %}
{# <div class="col-sm-offset-5 col-sm-2 text-center">#}
<a href="{{ cronslist }}"><i class="btn btn-primary waves-input-wrapper waves-effect"
style="color:#fff;background:#286090">
<input class="waves-button-input has-value" type="button" value="Cancel"
style="background-color:rgba(0,0,0,0);">
</i></a>
</div>
</div>
</div>
<div class="col-md-6">
<div class="row">
<div class="col-md-10">
<div style="text-align:center">
<label class="col-md-4">Param</label>
<label class="col-md-6">Value</label>
</div>
<div id="params"></div>
<!-- The template for adding new field -->
<template>
<div class="form-group">
<div class="col-md-4">
<input type="text" class="form-control param-x" placeholder="Task"/>
</div>
<div class="col-md-6">
<input type="text" class="form-control value-x" placeholder="Task"/>
</div>
</div>
<div class="col-md-10">
<hr>
</div>
</template>
</div>
<div class="col-md-2">
<label class="col-md-2">Add</label>
<button id="addParam" type="button" class="btn btn-default addButton"><i class="fa fa-plus"></i></button>
</div>
</div>
</div>
</div>

How to save values to database using AngularJS (Django Frame Work)

Hi my project works on Django framework with some use of AngularJS. What I need to achieve is when I click on submit on my page(html), it should save all the values I entered into the Database. I heard that I just need a simple submit button and main changes are in views.py. I am very new to Django as well as AngularJS. The following is my codes. Thanks in advance.
Html and AngularJS:
{% extends "base.html" %}
{% load static %}
{% block stylesheets %}
<link href="{% static 'css/xxg.css' %}" rel="stylesheet">
{% endblock %}
{% block mainbody %}
<br><br>
<div class="well">
<div class="well" ng-controller="LayerCtrl">
<table>
<tr>
<td>
<div class="input-group">
<span class="input-group-addon">jj</span>
<select class="form-control" name="jj">
{% for f in fab %}
<option value="{{f}}">{{f}}</option>
{% endfor %}
</select>
</div>
</td>
<td>
<div class="input-group">
{% for f in jj%}
{% if f == '1' %}
<span class="input-group-addon">yy</span>
<select class="form-control" ng-model="rr" ng-options="l.value as l.label for l in yyy"></select>
{% endif %}
{% if f == '8' %}
<span class="input-group-addon">tt</span>
<select class="form-control" ng-model="selected_technode" ng-options="l.value as l.label for l in rrr"></select>
{% endif %}
{% endfor %}
</div>
</td>
<td>
<div class="input-group">
<span class="input-group-addon">DD</span>
<!--<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">-->
{%verbatim%}
<select class="form-control" ng-model="selected_dd" ng-options="l as l for l in tt"></select>
{%endverbatim%}
</div>
</td>
</tr>
</table>
</div>
<div><h3>history:</h3></div>
<br/><br/>
<div ng-controller="AlertDemoCtrl">
<table class="table">
{% verbatim %}
<tr>
<td class="input-group" ng-repeat="(k,v) in alerts">
<span class="input-group-addon" ng-hide="v.hide">Check {{ k }}</span>
<span ng-hide="v.hide">
<input type="text" class="form-control" placeholder="Add gg here" ng-model="v.input">
<b>QQQ</b><input type="radio" name="{{ k }}" value="fc" ng-model="v.props">
<b>issue</b><input type="radio" name="{{ k }}" value="rr" ng-model="v.props">
<b>risk</b><input type="radio" name="{{ k }}" value="dr" ng-model="v.props">
<a type="reset" ng-click="reset()">
<span class="glyphicon glyphicon-repeat"></span>
</a>
<a href="" ng-click="remove(v)">
<span class="glyphicon glyphicon-trash"></span></a>
</span>
{% endverbatim %}
<tr>
<td>
<button type="button" class='btn btn-info' ng-click="addAlert()">
<span class="glyphicon glyphicon-plus"></span>
Add</button>
<button type="reset" ng-click="reset()" class="btn btn-danger">
<span class="glyphicon glyphicon-repeat"></span>
Reset All</button>
</td>
</tr>
</table>
</div>
<table class="table">
<!--IMPORT FILE-->
<tr>
<td>
<div style="position:relative;">
<a class='btn btn-primary' href='javascript:;' disabled>
</td>
</tr>
<!--ADD COMMENTS-->
<tr>
<td>
Add Comments*<div class="span5"><textarea name="bugnote_text" placeholder="Add comments here (max=600 characters)" rows="3" class="span10 ng-pristine
ng-valid ng-valid-maxlength" ng-maxlength="600"></textarea></div>
</td>
<td>
Add ftt*<input type="text" class="form-control" placeholder="Add ftthere">
</td>
</tr>
<form ng-submit="submit()" ng-controller="ExampleController">
<tr>
<td>
<button type="submit" id="submit" ngClick="Submit" class="btn btn-small btn-success"><span class="glyphicon glyphicon-pencil"></span> Submit</button>
<button class="btn btn-small btn-grey"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
</td>
</tr>
</form>
</table>
</div>
{% endblock %}
{% block extrascript %}
{{ ngapp }}.controller("LayerCtrl", function ($scope, $http, $resource){
var layerresource_url = $resource("{% url 'api_list' 'v1' 'layer' %}");
console.log('initializing....')
$scope.$watch('yy', function () {
<!--alert($scope.yy);-->
$scope.update_layer();
});
$scope.update_layer = function(){;
console.log('Stage1: Initializing Primary Data... ');
layerresource_url.get({techtype__contains: $scope.selected, limit:1500},
function(data){
$scope.list = data['objects'][0]['layer'];
console.log($scope.layerlist);
},function(data, status){
console.log('Stage1: Internal error while loading initial data:'+status );
<!--alert('internal error');-->
}
);
};
});
{{ ngapp }}.controller("AlertDemoCtrl", function ($scope, $http, $resource){
$scope.alerts = [];
$scope.addAlert = function() {
$scope.alerts.push({msg: 'Another alert!', props : 0, input : ""});
};
$scope.closeAlert = function(index) {
$scope.alerts.splice(index, 1);
};
$scope.reset = function() {
angular.forEach($scope.alerts, function(v){
v.input = "";
v.props = 0;
});
};
$scope.remove = function(v){
v.hide = 1;
}
$scope.reset();
});
{% endblock %}
You can use AJAX if you don't want to use forms. In AngularJS, it would look like this. Note your controller should have the needed arguments:
$scope.addsomething = function() {
token = $window.localStorage.token;
//data to be submitted
$scope.data = {"name": $scope.name,"project": project_id,"some_url": someURL,"status": "1","type": 1};
$http.defaults.headers.common.Authorization = 'token '+$window.localStorage.token;
req = $http({
method: "POST",
url:"your_url/",
data:$scope.data,
headers: {
'Content-Type': 'application/json'
},
});
req.success(function(data,status) {
//do something on success
});
req.error(function(data, status, headers, config) {
//do something on error
});
}
On your backend you just have to point this URL to a view which will save it in the database. Hope this helps.

Categories

Resources