Angular dataTables with Ajax Source - angular-datatables

I'm trying to load data from an ajax source into angular datatable but it's not even hitting the ajax call.
var analyzer=angular.module('analyzer', ['datatables']);
analyzer.controller('WithAjaxCtrl', WithAjaxCtrl);
function WithAjaxCtrl(DTOptionsBuilder, DTColumnBuilder) {
var vm = this;
$scope.dtOptions = DTOptionsBuilder.fromSource('/analyzer/List')
$scope.dtColumns = [
DTColumnBuilder.newColumn('BuildName').withTitle('Name'),
DTColumnBuilder.newColumn('Total').withTitle('Total'),
DTColumnBuilder.newColumn('Passed').withTitle('Passed'),
DTColumnBuilder.newColumn('Failed').withTitle('Failed')
];
}
Here's the html code for the table-
<div ng-controller="WithAjaxCtrl">
<table datatable="" dt-options="dtOptions" dt-columns="dtColumns" class="row-border hover"></table>
</div>
data from ajax source is in the form -
{"responseCode":0,"responseData":[{"Name":"Rob","Total":6273,"Passed":5874,"Failed":399}]}
So will i have to define the datasrc ?

Yes, you need to specify the dataSrc since your rows is contained in responseData, not in the default or expected data property. In angular dataTables there is an option setter named withDataProp() :
$scope.dtOptions = DTOptionsBuilder.fromSource('/analyzer/List')
.withDataProp('responseData')
Cannot link directly but look at https://l-lin.github.io/angular-datatables/#/api

Related

Dynamic form Issue in Angular

Scenario :
A form is generated dynamically, I used this tutorial to create the form dynamically. When I click "Submit" button, the form value I get in the component is
ts :
doSubmitICR(form) {
console.log(form.value);
}
form.value has the following values
{
CaptainPoint:"0",
Category:"restaurant",
Description:"Test",
DisplayDept:"kitchen",
Group:"restaurant",
GuestPoint:"0",
ItemCode:"1",
ItemName:"Test Item",
PrintingDept:"frontoffice",
SalesRate:"3",
SubGroup:"restaurant",
TAX1:true,
TAX2:true,
TabDisplay:"restaurant",
Unit:"restaurant"
}
TAX1 and TAX2 are dynamic, those form controls were created from a tax table, If the table has TAX3 and TAX4, then instead of TAX1 and TAX2 in the above form, TAX3 and TAX4 form control is generated.
Issue :
If the TAXs are dynamic, how can I pass these values to Web service say WebAPI2 as a model?
Is it possible to filter only the TAX element from the form.value?
Any advice would be appreciated. Thank you.
The solution from alexKhymenko should work well. Alternatively, if the values you want to submit to the API will always have the format of TAX{d}, where d is some combination of digits, you could use the following to get just those values on a request object:
let request = {};
Object.keys(form.value).forEach(key => {
if(/^TAX[\d]+$/.test(key))
request[key] = form.value[key]
});

Angularfire: How to Filter with a Specific key or ID

So here is my quick code.
var thisisformykeyorid =$scope.id;
var ref = firebase.database().ref('/myusers/').child("users");
$scope.users= $firebaseArray(ref);
var query = ref.orderByChild("timestamp").limitToLast(100);
$scope.filteruser= $firebaseArray(query);
In my HTML is
<div ng-repeat="samplein filteruser>
<h2>{{ sample.firstname}}</h2>
<p>{{ sample.age}}</p>
</div>
So in firebase there are unique id or keys for each set of data.
How do i add a filter or query to select a set of data from firebase using my variable ? (assuming $scope.id is a unique key) Please be guided that i dont want to use ng-repeat anymore because i only want to view only 1 set of data. Need help
If you know what object you want to display, you can use $firebaseObject instead of $firebaseArray:
var ref = firebase.database().ref('/myusers/').child("users");
$scope.user = $firebaseObject(ref.child($scope.id));
And then display it in your HTML with:
<div >
<h2>{{user.firstname}}</h2>
<p>{{user.age}}</p>
</div>

Using Meteor what is the JS equivelent of {{{member}}}

I have a meteor helper that uses a reactive variable in a find to get a unique document using an id. My item button template looks like this:
<template name = "itemButton" >
<div class = "itemButton" name = {{_id}}>
{{{title}}}
</div>
</template>
using a reactive variable:
Template.landing.onCreated(function _OnCreated() {
this.f = new ReactiveVar();
this.f.set(false);
const handle = Meteor.subscribe("Feed");
});
now I have a method in a template several itemButton.
Template.landing.events({
'click .itemButton' : function(event, template){
alert(event.target.name);
template.f.set(event.target.name);
}
});
and I would like to use that name in a helper that would use this value as the _id.
Template.landing.helpers({
"GetFocus": function(){
alert(Template.instance().f.get()); // alerts undefined...
return(items.find({'_id':Template.instance().f.get()}));
}
});
So where I expect GetFocus to give me the document that generated the button I don't seem to be so lucky. Let me know if I can provide any additional clarification, and as always your input is appreciated.
Where I have template.f.set(event.target.name); I needed template.f.set(event.currentTarget.getAttribute('data-id')); where the html uses data-id instead of name.

Flask request not returning any info from select

I'm trying to set up a simple select dropdown form with Flask. Based on the option chosen, I grab different data from my database, and display it back into a div on my html template. But I can't seem to get the Flask request to register any of the select options. When I print request.form or request.args, I always get empty Dicts. It's probably something simple I'm missing but I can't seem to find the problem. I've gotten this to work with several input and button forms, but I can't get it to work right for selects.
Here is a bit of my html template code, with the form and select. I've tried both GET and POST method in the form.
<div class="options" id="options">
<form class="form-horizontal container-fluid" role="form" method="GET" action="exploresn2.html">
<div class="form-group">
<label for="xaxis" class="col-sm-2 control-label">X-axis:</label>
<div class="col-sm-2">
<select name="xaxis" class="form-control" id="xaxis">
<option selected value="mjd" id="mjd">MJD</option>
<option value="seeing" id="seeing">Seeing</option>
<option value="airmass" id="airmass">Airmass</option>
<option value="hourangle" id="hourangle">Hour Angle</option>
</select>
</div>
</div>
</form>
</div>
In Flask, at first, I tried inside my app
import flask
from flask import request, render_template, send_from_directory, current_app
explore_page = flask.Blueprint("explore_page", __name__)
#explore_page.route('/exploresn2.html', methods=['GET','POST'])
def explore():
xaxis = str(request.args.get("xaxis", "any"))
.... [populate new xaxis variable based on request option selected]
exploreDict['xaxis'] = xaxis
return render_template("exploresn2.html", **exploreDict)
or
mjd = valueFromRequest(key='mjd', request=request, default=None)
if mjd:
mjds = [int(exp.platedbExposure.start_time/(24*3600)) for exp in exposures]
xaxis = mjds
exploreDict['xaxis'] = xaxis
to look for and grab a specific values, or in the first case, any value select. The valueFromRequest is function that grabs data from either GET or POST requests.
but this returns nothing, and then I tried just printing the entire request.args (or request.form) and it returns and empty Dict. Everything I try it still returns empty Dicts. So I'm missing some set up somewhere I think but the form looks right to me?
I'm not sure if this is the actual answer to this problem that I was looking for, but here is what I came up with. I couldn't actually get the Flask to accept a GET request into the original explore method defined, so I implemented a new method in Flask to return a JSON object
#explore_page.route('/getdata', methods=['GET','POST'])
def getData(name=None):
name = str(request.args.get("xaxis", "mjd"))
xaxis = 'populate new xaxis data based on value of name'
data = '(x,y) data array filled with values for plotting'
axisrange = range of x,y data for axes for plot
return jsonify(result=data, range=axisrange)
and then I just made a GET request via javascript to that method whenever the select button changes. So in my exploresn2.html template I have (using Flot for plotting)
$("#xaxis").change(function(){
var newname = $("#xaxis :selected").text();
var axes = plot.getAxes();
options = plot.getOptions();
var plotdata = plot.getData();
// make a GET request and return new data
$.getJSON($SCRIPT_ROOT + '/getdata', {'xaxis':$("#xaxis :selected").val()},
function(newdata){
// set new data
for (var i = 0; i < plotdata.length; ++i) {
plotdata[i].data = newdata.result[plotdata[i].label];
}
// set new axes
axes.xaxis.options.panRange = [newdata.range[0]-50,newdata.range[1]+50];
axes.xaxis.options.axisLabel = newname;
axes.xaxis.options.min = newdata.range[0]-1;
axes.xaxis.options.max = newdata.range[1]+1;
axes.yaxis.options.min = newdata.range[2];
axes.yaxis.options.max = newdata.range[3];
// redraw plot
plot.setData(plotdata);
plot.setupGrid();
plot.draw();
});
});

How to serialize html form in dart as a string for submission

In jQuery, there is a function to serialize a form element so for example I can submit it as an ajax request.
Let's say we have a form such as this:
<form id="form">
<select name="single">
<option>Single</option>
<option selected="selected">Single2</option>
</select>
<input type="checkbox" name="check" value="check1" id="ch1">
<input name="otherName" value="textValue" type="text">
</form>
If I do this with the help of jquery
var str = $( "form" ).serialize();
console.log(str);
the result would be
single=Single2&check=check1&otherName=textValue
Is there such functionality in dart's FormElement or I have to code it myself? Thanks.
I came up with my own simple solution that might not work in all cases (but for me it is workikng). The procedure is this:
First we need to extract all input or select element names and values from the form into Dart's Map, so the element name will be the key and value the value (e.g. {'single': 'Single2'}).
Then we will loop through this Map and manually create the resulting string.
The code might look something like this:
FormElement form = querySelector('#my-form'); // To select the form
Map data = {};
// Form elements to extract {name: value} from
final formElementSelectors = "select, input";
form.querySelectorAll(formElementSelectors).forEach((SelectElement el) {
data[el.name] = el.value;
});
var parameters = "";
for (var key in data.keys) {
if (parameters.isNotEmpty) {
parameters += "&";
}
parameters += '$key=${data[key]}';
}
Parameters should now contain all the {name: value} pairs from the specified form.
I haven't seen anything like that yet.
In this example Seth Ladd uses Polymers template to assign the form field values to a class which get's serialized.