How to make a function update the value of angular inputs - javascript

When I select one of the cards on the page below, I wish to have the value of the inputs updated with values from a JSON object
The json:
{
"status": true,
"data": [
{
"id": 1,
"pessoa_id": 75505,
"created_at": "2022-02-01T17: 42: 46.000000Z",
"holder": "LEONARDO LIMA",
"validade": "2026-06-01",
"bandeira": "Mastercard"
}
]
}
The json value is on the variable "responseData"
renderTokenCard() {
this.mundipaggS.checkToken().subscribe((response: any) => {
console.log(JSON.stringify(response));
this.cartS.tokenCard = response;
this.responseData = response;
console.log(JSON.parse(JSON.stringify(response)));
},);
}
the function that is linked to the select action:
SelecionarCartao() {
this.mundipaggS.postToken(this.responseData)
console.log(this.responseData)
}
I wanted to get the responseData value and make a post for the postToken
The HTML
<div class="form-group ">
<label for="ncartao">Número do cartão <span class="text-danger"> *</span></label>
<input name="card-number" maxlength="19" #cardNumber formControlName="digiNumero" id="ncartao" type="text"
class="form-control col-lg-6 ">
</div>
<div class="form-group">
<label for="nomeimpresso">Nome <b>impresso</b> no cartão<span class="text-danger"> *</span></label>
<input #nomeImpresso formControlName="digiNome" name="holder-name" id="nomeimpresso" class="form-control col-lg-6"
type="text">
</div>

"Think in functions". If you has a function like
getGroup(data:any=null)
{
//data will be the properties by defect and, using spread operator,
//replace the properties by the data object
data={
id: 0,
pessoa_id:0,
created_at:"",
holder: "",
validade: "",
bandeira:"",
...data
}
return new FormGroup({
id: new FormControl(data.id),
pessoa_id: new FormControl(data.pessoa_id),
created_at:new FormControl(data.created_at),,
holder: new FormControl(data.holder),,
validade: new FormControl(data.validade),,
bandeira:new FormControl(data.bandeira),}
})
}
Each change in "Meus Cartoes"
change(bandeira:string)
{
const data=this.responseData.data.find(x=>x.bandeira==bandeira)
if (data)
this.form=getGroup(data) //<--a form with all the data
else
this.form=getGroup({bandeira:bandeira}) //<--a form with the "bandeira"
}
NOTE: really the "form" need split the "validate", get the "numero do cartao" and the "nome_impreso"...

Related

How to add values into JSON-array (node.js/mongoose)

I'm using mongoose, adding values from HTML and saving to db with help of mongoose. I'm having issue adding value from req.body.chapter into array from HTML.
Route:
const newBook = {
book: req.body.book,
summary: req.body.summary,
chapters: //how to add value into chapter-array?
}
Book-model:
const BookSchema = new Schema({
Title: {
type: String,
required: true
},
Summary: {
type: String,
required: true
},
chapters : [{
chapter: {
type: String,
required: true
}]
});
HTML:
<div class="form-group">
<label for="book">Title:</label>
<input type="text" class="form-control" name="book" required>
</div>
<div class="form-group">
<label for="Summary">Summary:</label>
<input type="text" class="form-control" name="Summary" required>
</div>
<div class="form-group">
<label for="chapter">chapter:</label>
<input type="text" class="form-control" name="chapter" required>
</div>
So if the data looks like this, you can just put it in:
req.body.chapters = ["1", "3"];
Route:
const newBook = {
book: req.body.book,
summary: req.body.summary,
chapters: req.body.chapters
}
If you just want to add the chapters to existing data, then have a look at Using Mongoose / MongoDB $addToSet functionality on array of objects

Get name and id of autocomplete suggestions into input field

I have the code below, which I use to type and suggest a few relation names in an input field. The data variable right now returns only names like:
var data = ["name": "Relation 1", "name":"Relation 2"]
I modified it and now it has data like:
var data = [
{"id":1,"name":"Foo"},
{"id":2,"name":"Bar"},
{"id":3,"name":"Foo Bar"}
];
How do I append the id of the selected name in the id input?
$('input.relation').typeahead({
source: function (query, process) {
return $.get('live_search.php?filter=relation', { query: query }, function (data) {
console.log(data);
data = $.parseJSON(data);
return process(data);
});
}
});
<div class="form-group">
<label for="relation"> Relation </label>
<input class="relation form-control" type="text">
<input class="relation-id form-control" type="text" name="id">
</div>

Save multiple Objects from Angular to Sequelize

I'm using mean.js to create a system and I change the mongoose part for sequelize and I trying to save multiple Objects from Angular to my database through sequelize.
I followed this answer to create multiple inputs dynamically on the Dia (Day) option for multiple schedules.
And I have my controller like this:
$scope.horarios = [];
$scope.itemsToAdd = [{
Day: '',
StartHour: '',
EndHour: ''
}];
$scope.add = function(itemToAdd) {
var index = $scope.itemsToAdd.indexOf(itemToAdd);
$scope.itemsToAdd.splice(index, 1);
$scope.horarios.push(angular.copy(itemToAdd))
};
$scope.addNew = function() {
$scope.itemsToAdd.push({
Day: '',
StartHour: '',
EndHour: ''
});
console.log($scope.itemsToAdd);
};
and view
<div class="col-xs-12" style="padding: 0" ng-repeat="itemToAdd in itemsToAdd">
<div class="form-group col-xs-12 col-sm-5" >
<label for="Days">Dia</label> <select class="form-control col-xs-12 col-sm-6" data-ng-model="itemToAdd.Day" id="Days" name="Days">
<option value="">---Seleccione uno---</option>
....
</select>
</div>
<div class="form-group col-xs-5 col-sm-3">
<label class="control-label" for="startHour">Hora Inicio</label> <input class="form-control" id="startHour" name="startHour" ng-model="itemToAdd.StartHour" type="time">
</div>
<div class="form-group col-xs-5 col-sm-3">
<label class="control-label" for="endHour">Hora Termino</label> <input class="form-control" id="endHour" name="endHour" ng-model="itemToAdd.EndHour" type="time">
</div>
<div class="col-xs-2 col-sm-1">
<button ng-click="addNew()" class="btn btn-success" style="position: relative; top:26px"><i class="glyphicon glyphicon-plus"></i></button>
</div>
</div>
Then I have my both controllers on client side with Angular:
// Create new course
$scope.create = function( isValid ) {
// Create new course object
var course = new Courses( $scope.course );
course.Schedule = $scope.itemsToAdd;
console.log($scope.course);
// Redirect after save
course.$save( function( response ) {
$scope.closeThisDialog();
notify( 'Genial. El Curso ha sido registrada exitosamente' );
// Clear form fields
$scope.course = '';
$scope.schedule = '';
}, function( errorResponse ) {
$scope.error = errorResponse.data.message;
} );
};
And sequelize:
exports.create = function(req, res) {
var schedule = req.body.Schedule;
req.body.schedule = undefined;
// req.body.userId = req.user.id;
db.Course.create(req.body)
.then(function(course) {
if (!course) {
return res.send('users/signup', {
errors: 'Could not create the course'
});
} else {
schedule.CourseId = course.dataValues.id;
db.Schedule.create(schedule)
.then(function(schedule) {
for (var i = schedule.dataValues.length - 1; i >= 0; i++) {
course.schedule = schedule.dataValues[i];
}
// course.schedule = schedule.dataValues;
})
.catch(function(err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
});
return res.jsonp(course);
}
})
.catch(function(err) {
return res.status(400)
.send({
message: errorHandler.getErrorMessage(err)
});
});
};
But honestly I don't have a clue how to save it or if my Angular controller is even the correct way to do it. Hope you can help me or give me hint how to do it.
In addition to updating a single instance, you can also create, update, and delete multiple instances at once. The functions you are looking for are called
Model.bulkCreat
http://docs.sequelizejs.com/en/2.0/docs/instances/#working-in-bulk-creating-updating-and-destroying-multiple-rows-at-once

Angular - Mongoose : Can't manipulate dates

I have been searching for a long while for solution, but nothing helped me.
I have an Angular JS app which runs with Mongoose and Express.
I want to store date as object from a simple form.
But when I submit my form, dates are stored as String and not as Objects.
So I can't do something like :
tache.start.getDate();
Here is my form :
<form name="formTache" ng-submit="addTache(tache)">
<div class="form-group row">
<div class="col-lg-12">
<input name="name" class="form-control" placeholder="Nom" type="text" ng-model="tache.title"/>
</div>
</div>
<div class="form-group row">
<div class="col-lg-12">
<input id="date" name="date" class="form-control" placeholder="Date" ng-model="tache.start" type="date"/>
</div>
</div>
<div class="form-group row">
<div class="text-right col-lg-12">
<button type="submit" class="btn btn-default">Ajouter</button>
</div>
</div>
Here is my Mongoose Schema :
var restful = require('node-restful');
var mongoose = restful.mongoose;
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var tachesSchema = new mongoose.Schema({
title : String,
start: {type: Date, default: new Date()},
});
var tachesModel = mongoose.model('taches', tachesSchema);
module.exports = restful.model('taches', tachesSchema);
Here is my Controller :
angular.module('personaldashboard.tache', [])
.controller('TachesCtrl', function($scope, Taches, Progress, toaster) {
$scope.tache = new Taches();
var refreshTache = function() {
$scope.taches = Taches.query();
$scope.tache = ''
}
refreshTache();
$scope.addTache = function(tache) {
Taches.save(tache,function(tache){
refreshTache();
});
};
$scope.updateTache = function(tache) {
tache.$update(function(){
refreshTache();
});
};
$scope.removeTache = function(tache) {
tache.$delete(function(){
refreshTache();
});
};
$scope.editTache = function(id) {
$scope.tache = Taches.get({ id: id });
};
$scope.deselectTache = function() {
$scope.tache = ''
}
$scope.editTache_Projet = function(tache, projetId) {
tache.projet = projetId;
tache.$update(function(){
refreshTache();
});
};
});
Here is what I get :
{ "_id": "58a99df24975ad0104c692b1", "title": "Test", "start": "2017-02-24T23:00:00.000Z" }
So why do I get a string like "2017-02-24T23:00:00.000Z" for my date instead of an object whereas my Mongoose schema specify start: {type: Date, default: new Date()} ?
Thanks for your help.
EDIT
Thanks to Saurabh Agrawal, I tried to convert the date when submiting in the controller :
$scope.addTache = function(tache) {
tache.start = new Date(tache.start);
tache.end = new Date(tache.end);
Taches.save(tache,function(tache){
refreshTache();
});
};
Sadly, this changed nothing :(
I still have a date as string
"2017-02-20T23:00:00.000Z"
EDIT
I also tried to add a directive
.directive("formatDate", function(){
return {
scope: {ngModel:'='},
link: function(scope) {
if (scope.ngModel) {
scope.ngModel = new Date(scope.ngModel);
}
}
}
})
and call it in my form
<form name="formTache" ng-submit="addTache(tache)">
<div class="form-group row">
<div class="col-lg-12">
<input name="name" class="form-control" placeholder="Nom" type="text" ng-model="tache.title"/>
</div>
</div>
<div class="form-group row">
<div class="col-lg-12">
<input id="date" name="date" class="form-control" placeholder="Date" ng-model="tache.start" type="date" formatDate/>
</div>
</div>
<div class="form-group row">
<div class="text-right col-lg-12">
<button type="submit" class="btn btn-default">Ajouter</button>
</div>
</div>
But nothing changes.
Any other ideas ?
By searching, I 've found that I was missing the real problem.
My dates are date objects.
When i do this
$scope.test = new Date([2017,2,15]);
<pre>{{test}}</pre>
<pre>{{test.getDate()}}</pre>
I get
"2017-02-14T23:00:00.000Z" and 15
So date displaying like "2017-02-14T23:00:00.000Z" are objects.
But in my case, when i try to do the same with a date whitch is in another object like in this schema :
var tachesSchema = new mongoose.Schema({
title : String,
start: {type: Date, default: new Date()},
end: {type: Date, default: new Date()},
comment : String,
state : Boolean,
projet : { type: ObjectId, ref: 'Projets' }
});
I get nothing :(
This code :
{{tache.start}}
displays the date like this "2017-02-20T23:00:00.000Z"
but
<pre>{{tache.start.getDate()}}</pre>
displays nothing.
What I missed ?

Data from form are not passed to submit function - Using Angular

I have a problem with a form implemented using Angular.
defining my variable in the scope I can see value (pre-filled) in the html form (ng-model), but when I submit the function, the new data (inserted by the users) don't update the model ($scope var) in the controller.
Here a snipped of my html and js controller:
<form class="form-horizontal">
<h3>Citizen</h3>
<div class="row">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="name" ng-model="ticketDetails.ticketDetails.name" placeholder="Name">
</div>
<label for="DOB" class="col-sm-2 control-label">Birth date</label>
<div class="col-sm-4">
<input type="date" class="form-control" id="DOB" ng-model="ticketDetails.ticketDetails.DOB" placeholder="Birth Date">
</div>
</div>
</div>...
and the controller
angular.module('demoApp', [])
.controller('mainController', function($scope, $http) {
// $scope.ticketDetails = { "ticketDetails" : {
// "name": "Giovanni Vigorelli",
// "DOB": "1974-05-02T05:07:13Z",
// "driverLicense": "e345234",
// "registration": "hdd843",
// "ticketType": "Speeding",
// "date": "2016-05-02T05:07:13Z",
// "location": "34 Queen St, Auckland",
// "ticketId": "12345",
// "officer": "Oscar Nice"
// }};
$scope.ticketDetails = { "ticketDetails": {}};
$scope.ticketDetails.ticketDetails.ticketId = (+new Date).toString(36).slice(-5);
// The following should be the authentucated user
$scope.ticketDetails.ticketDetails.officer = "Oscar Nice";
var bpmQueryParam = 'action=start&bpdId=25.c1206b63-1e94-4aaa-9dc1-76363270b441&processAppId=2066.d0e91cc6-a515-4965-ba6f-516bdbddcb00&params=' + JSON.stringify($scope.ticketDetails) + '&parts=all';
$scope.startProcess = function(){
console.log('### In startProcess');
console.log("### bpmQueryParam: " + bpmQueryParam);
var req = {
method: 'POST',
headers: {'Authorization': 'Basic YWRtaW46YWRtaW4=','Accept': 'application/json','Access-Control-Allow-Origin': '*', 'Content-Type': 'application/x-www-form-urlencoded'},
url: 'http://1.1.1.1:9080/rest/bpm/wle/v1/process',
data: bpmQueryParam
}
Basically I don't a bidirectional sync of the var, just from controller to view and NOT from view to controller.
Any advice?
Cheers, Giovanni
I suppose $scope.startProcess is your submit function. Please write the following line inside the submit function:
var bpmQueryParam = 'action=start&bpdId=25.c1206b63-1e94-4aaa-9dc1-76363270b441&processAppId=2066.d0e91cc6-a515-4965-ba6f-516bdbddcb00&params=' + JSON.stringify($scope.ticketDetails) + '&parts=all';
You have wriiten this code outside the function, therefore it is taking the initial data for $scope.ticketDetails variable.
You should write it as following:
$scope.startProcess = function(){
var bpmQueryParam = 'action=start&bpdId=25.c1206b63-1e94-4aaa-9dc1-76363270b441&processAppId=2066.d0e91cc6-a515-4965-ba6f-516bdbddcb00&params=' + JSON.stringify($scope.ticketDetails) + '&parts=all';
// Rest of your code
}

Categories