So I have a problem in my CRUD application using Node JS, Express, and Mongo DB. Actually, I am just following this tutorial but I get stuck on the UPDATE part. I am able to CREATE, READ, and DELETE values from database already, but I don't know why I keep getting this error whenever I try to UPDATE my data.
I found the error is from my controller.js file and here's the code:
exports.update = (req,res)=>{
if(!req.body){
return res
.status(400)
.send({message:"Record to be updated can not be empty!"})
}
const id = req.params.id;
studentDb.findByIdAndUpdate(id,req.body,{userFindAndModify:false})
.then(data=>{
if(!data){
res.status(404).send({message:`Cannot update student record with ID ${id}. Maybe record not found.`})
}else{
res.send(data)
}
})
.catch(err=>{
res.status(500).send({message:`Error in updating student record with id=${id}.` + err})
})
}
My hypothesis is that the objectID goes on the first model in my schema because whenever I check the console when I run the application, the last value of the model in my schema, the "contact" goes undefined.
The ERROR:
I can provide the other codes related to this if my question is still unclear. Thank you in advance for answering! I've been stuck here for hours already.
EDIT
Here's the additional front-end code
(this is the FORM part from my update_student.ejs where I update the data):
<!-- form handling -->
<form method="POST" id="update_student">
<div class="new_student">
<div class="form-group">
<div class="row">
<div class="col-lg-4">
<label for="firstName" class="text-muted">First Name</label><br>
<input type="hidden" name="id" value="<%=students._id%>">
<input type="text" name="firstName" value="<%=students.firstName%>" placeholder="Corki">
</div>
<div class="col-lg-4">
<label for="middleName" class="text-muted">Middle Name</label><br>
<input type="text" name="middleName" value="<%=students.middleName%>" placeholder="Vi">
</div>
<div class="col-lg-4">
<label for="lastName" class="text-muted">Last Name</label><br>
<input type="text" name="lastName" value="<%=students.lastName%>" placeholder="Fortune">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-4">
<label for="gender" class="text-muted">Gender</label><br>
<div class="radio inline">
<input type="radio" id="radio-2" name="gender" value="Male" <% if(students.gender == "Male"){ %>checked <% } %>>
<label for="radio-2" class="radio-label">Male</label>
</div>
<div class="radio inline">
<input type="radio"id="radio-3" name="gender" value="Female" <% if(students.gender == "Female"){ %>checked <% } %>>
<label for="radio-3" class="radio-label">Female</label>
</div>
</div>
<div class="col-md-8">
<div class="form-group">
<label for="birthday" class="text-muted">Birthday</label>
<input type="text" name="birthday" value="<%=students.birthday%>" placeholder="MM/DD/YYYY">
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<label for="program" class="text-muted">Program</label>
<input type="text" name="program" value="<%=students.program%>" placeholder="i.e. BSIT">
</div>
<div class="col-md-6">
<label for="yearLevel" class="text-muted">Year Level</label>
<select class="form-select" name="yearLevel">
<option value="">Select year level</option>
<option <% if(students.yearLevel == "First Year"){ %>selected <% } %> value="First Year">First Year</option>
<option <% if(students.yearLevel == "Second Year"){ %>selected <% } %> value="Second Year">Second Year</option>
<option <% if(students.yearLevel == "Third Year"){ %>selected <% } %> value="Third Year">Third Year</option>
<option <% if(students.yearLevel == "Fourth Year"){ %>selected <% } %> value="Fourth Year">Fourth Year</option>
<option <% if(students.yearLevel == "Fifth Year"){ %>selected <% } %> value="Fifth Year">Fifth Year</option>
<option <% if(students.yearLevel == "Masteral"){ %>selected <% } %> value="Masteral">Masteral</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<label for="email" class="text-muted">Email</label>
<input type="text" name="email" value="<%=students.email%>" placeholder="example#gmail.com">
</div>
<div class="form-group">
<label for="address" class="text-muted">Address</label>
<input type="text" name="address" value="<%=students.address%>" placeholder="Household No., Barangay, City, Province">
</div>
<div class="form-group">
<label for="contact" class="text-muted">Contact</label>
<input type="text" name="contact" value="<%=students.contact%>" placeholder="i.e 09XX-XXX-XXXX">
</div>
<div class="form-group">
<button type="submit" class="btn text-dark update">Save</button>
</div>
</div>
</form>
<!-- form handling -->
Code for my #update_student JS just in case:
$('#update_student').on("submit",(function(event){
event.preventDefault();
var unindexed_array = $(this).serializeArray();
var data = {}
$.map(unindexed_array,function(n,i){
data[n['firstName']] = n['value']
})
console.log(data);
var request={
"url": `http://localhost:1485/api/students/${data.id}`,
"method":"PUT",
"data" : data
}
$.ajax(request).done(function(response){
alert("Data updated successfully!");
})
}))
Thanks to Sir #Rajdeep Debnath 's help, I was able to look into may "unindexed_array" from my console.log and figured out that instead of data[n['firstName']] = n['value']
I should write data[n['name']] = n['value']
I wrote the former because I thought it is just the name of the variable but in actuality, it is like the "id" or "class" called in JavaScript. The form used "name" on the inputs (like <input type="text" name="program" value="<%=students.program%>" placeholder="i.e. BSIT"> from my code) so that's why it is the one called in the function instead.
Now my code for my #update_student JS goes like this:
$('#update_student').on("submit",(function(event){
event.preventDefault();
var unindexed_array = $(this).serializeArray();
var data = {}
$.map(unindexed_array,function(n,i){
data[n['name']] = n['value']
})
console.log(data);
var request={
"url": `http://localhost:1485/api/students/${data.id}`,
"method":"PUT",
"data" : data
}
$.ajax(request).done(function(response){
alert("Data updated successfully!");
})
}))
You just simply change your Url path with ``symbol instead of ''.
Just like that
var request={
"url": `http://localhost:1485/api/students/${data.id}`,
"method":"PUT",
"data" : data
}
I need to retrieve all older data of a form, before updating it to new one. I need those form data for a reporting purpose. It basically will be the version of a data.
I am working on #Nodejs #ExpressJS #EJS as template and #MONGODB,#mongoose.
Below are the images of the code! I am new to the programming so please help me with the coding part not describe it using coding Jargans!
Schema Snippet
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
// define the schema for our user model
var procedureschema = mongoose.Schema({
proceduretype : String,
procedurename : String,
procedurenumber : String,
scope : String,
status:{type:String,lowercase:true,enum:["draft", "active", "pending"]},
forms : String,
relatedprocedure : String,
norms : String,
qualityrecords : String,
expdate : String,
companyname : String,
version : String,
owner: String,
approver : String,
procedurefiles : String,
flowchart : String,
proceduredescription : String,
isotags : String,
departmentname : String
});
// generating a password hash
// create the model for users and expose it to our app
module.exports = mongoose.model('Procedure', procedureschema);
Form view EJS page
<% include sidebar.ejs %>
<div class="dt-content">
<!-- Page Header -->
<!-- <div class="dt-page__header">
<h1 class="dt-page__title">New Procedure</h1>
</div> -->
<!-- /page header -->
<!-- Grid -->
<div class="row">
<!-- Grid Item -->
<div class="col-xl-12">
<!-- Card -->
<div class="dt-card">
<div class="dt-card__header">
<!-- Card Heading -->
<div class="dt-card__heading">
<h3 class="dt-card__title">New Procedure</h3>
</div>
<!-- /card heading -->
<a type="button" href="/admin/add/procedure/forms" role="button" class="btn btn-dark mr-2 mb-2"> Add Forms</a>
<a type="button" href="/admin/add/procedure/type" role="button" class="btn btn-dark mr-2 mb-2"> Add Procedure Type</a>
<a type="button" href="/admin/add/procedure/norms" role="button" class="btn btn-dark mr-2 mb-2"> Add Norms</a>
<a type="button" href="/admin/add/procedure/tags" role="button" class="btn btn-dark mr-2 mb-2"> Add Procedure Tags</a>
</div>
<!-- Card Header -->
<!-- /card header -->
<div class="dt-card__body">
<form action="/admin/create/procedure" method="post" enctype="multipart/form-data">
<div class="form-row">
<div class="col-sm-6 mb-3">
<label>Procedure Type</label>
<div class="input-group">
<select class="custom-select" name="proceduretype" id="inputGroupSelect04">
<option selected>Choose Procedure Type</option>
<% procedurecat.forEach(function(data){%>
<option value="<%=data.category_name %>"><%=data.category_name %></option>
<%})%>
</select>
</div>
</div>
<div class="col-sm-6 mb-3">
<label>Procedure Name</label>
<input type="text" class="form-control" id="validationDefault03" name="procedurename" placeholder="Enter Procedure Name"
required>
</div>
<div class="col-sm-6 mb-3">
<label>Procedure Number</label>
<input type="number" class="form-control" name="procedurenumber" id="validationDefault03" placeholder="Enter Procedure Number"
required>
</div>
<div class="col-sm-6 mb-3">
<label>Scope</label>
<input type="text" class="form-control" id="validationDefault03" name="scope" placeholder="Enater Procedure Scope"
required>
</div>
<div class="col-sm-6 mb-3">
<label>Status</label>
<div class="input-group">
<select class="custom-select" name="status" id="inputGroupSelect04">
<option selected>Choose Status</option>
<option value="draft">Draft</option>
<option value="pending">Pending</option>
<option value="active">Active</option>
</select>
</div>
</div>
<div class="col-sm-6 mb-3">
<label>Forms</label>
<div class="input-group">
<select class="custom-select" name="forms" id="inputGroupSelect04">
<option selected>Choose Forms</option>
<% forms.forEach(function(data){%>
<option value="<%=data.forms_name %>"><%=data.forms_name %></option>
<%})%>
</select>
</div>
</div>
<div class="col-sm-6 mb-3">
<label>Related Procedure</label>
<div class="input-group">
<select class="custom-select" name="relatedprocedure" id="inputGroupSelect04">
<option selected>Choose Related Procedures</option>
<% proceduretitle.forEach(function(data){%>
<option value="<%=data.procedurename %>"><%=data.procedurename %></option>
<%})%>
</select>
</div>
</div>
<div class="col-sm-6 mb-3">
<label>Select Norms</label>
<div class="input-group">
<select class="custom-select" name="norms" id="inputGroupSelect04">
<option selected>Choose Norms</option>
<% norms.forEach(function(data){%>
<option value="<%=data.norms_name %>"><%=data.norms_name %></option>
<%})%>
</select>
</div>
</div>
<div class="col-sm-6 mb-3">
<label>Quality Records</label>
<input type="text" name="qualityrecords" class="form-control" id="validationDefault03"
placeholder="Enter Quality Records Here" required>
</div>
<div class="col-sm-6 mb-3">
<label>Expiration Date</label>
<div class="input-group date" id="date-time-picker-1" data-target-input="nearest">
<input type="text" name = "expdate" class="form-control datetimepicker-input" data-target="#date-time-picker-1" />
<div class="input-group-append" data-target="#date-time-picker-1" data-toggle="datetimepicker">
<div class="input-group-text"><i class="icon icon-calendar"></i></div>
</div>
</div>
</div>
<div class="col-sm-6 mb-3">
<label>Company Name</label>
<input type="text" value="<%= user.companyname %>" name="companyname" class="form-control" id="validationDefault03" readonly
>
</div>
<div class="col-sm-6 mb-3">
<label>Version</label>
<input type="number" step ="0.1" name="version" class="form-control" id="validationDefault03" placeholder="Auto Increased field"
required>
</div>
<div class="col-sm-6 mb-3">
<label>Owner</label>
<div class="input-group">
<select class="custom-select" name="owner" id="inputGroupSelect04">
<option selected>Choose Owner</option>
<% users.forEach(function(data){%>
<option value="<%=data.name %>"><%=data.name %></option>
<%})%>
</select>
</div>
</div>
<div class="col-sm-6 mb-3">
<label>Approver</label>
<div class="input-group">
<select class="custom-select" name="approver" id="inputGroupSelect04">
<option selected>Choose Approver</option>
<% users.forEach(function(data){%>
<option value="<%=data.name %>"><%=data.name %></option>
<%})%>
</select>
</div>
</div>
<div class="col-sm-6 mb-3">
<label>Departmnent Name</label>
<div class="input-group">
<select class="custom-select" name="departmentname" id="inputGroupSelect04">
<option selected>Choose Department Name</option>
<% department.forEach(function(data){%>
<option value="<%=data.departmentname %>"><%=data.departmentname %></option>
<%})%>
</select>
</div>
</div>
<div class="col-sm-12 mb-3 form-row">
<label class=" col-form-label text-sm-left" for="file-field">Attached Files</label>
<div class="col-md-12 col-sm-9">
<div class="custom-file">
<input type="file" name="procedurefiles" onchange="GetFileSizeNameAndType()" id="file" class="custom-file-input" id="file-field" multiple>
<label class="custom-file-label" for="file-field">Attacthed your files here ..</label>
</div>
</div>
<div class="form-row input-group">
<div class="col-md-6 col-sm-6 form-row">
<div id="fp"></div>
</div>
</div>
</div>
<div class=" col-sm-12 mb-4 ">
<label class=" text-sm-left mb-4">Flowchart</label>
<button type="button" href="javascript:void(0)" role="button" class="btn btn-dark mr-2 mb-2">Design your flowchart</button>
</div>
<div class=" col-sm-12 mb-4 ">
<label>Description</label>
<textarea class=" col-sm-12 mb-4" name="proceduredescription" id="summernote"></textarea>
</div>
</div>
<hr class="border-dashed my-8">
<div class=" form-row mb-4 ">
<label class="col-md-2 col-sm-3 text-sm-right mb-4 mb-sm-0">Read Confirmation</label>
<div class="col-md-10 col-sm-9">
<!-- Checkbox -->
<div class="custom-control custom-checkbox custom-control-inline">
<input type="checkbox" id="customcheckboxInline1" name="customcheckboxInline1"
class="custom-control-input" checked>
<label class="custom-control-label" for="customcheckboxInline1"></label>
</div>
</div>
</div>
<hr class="border-dashed my-8">
<div class="form-group form-row mb-0 col-md-12">
<button type="submit" class="btn btn-primary text-uppercase">Submit this procedure</button>
</div>
</form>
</div>
<!-- Card Body -->
</div>
<!-- /card body -->
</div>
<!-- /card -->
</div>
<!-- /grid item -->
</div>
<!-- /grid -->
<!-- /site content -->
<% include footer.ejs %>
<script>
$(document).ready(function() {
$('#summernote').summernote();
});</script>
<script>
function GetFileSizeNameAndType()
{
var fi = document.getElementById('file'); // GET THE FILE INPUT AS VARIABLE.
var totalFileSize = 0;
// VALIDATE OR CHECK IF ANY FILE IS SELECTED.
if (fi.files.length > 0)
{
// RUN A LOOP TO CHECK EACH SELECTED FILE.
for (var i = 0; i <= fi.files.length - 1; i++)
{
//ACCESS THE SIZE PROPERTY OF THE ITEM OBJECT IN FILES COLLECTION. IN THIS WAY ALSO GET OTHER PROPERTIES LIKE FILENAME AND FILETYPE
var fsize = fi.files.item(i).size;
totalFileSize = totalFileSize + fsize;
document.getElementById('fp').innerHTML = document.getElementById('fp').innerHTML + '<br /> ' + 'File Name is <b>' + fi.files.item(i).name + "</b>.";
}
}
document.getElementById('divTotalSize').innerHTML = "Total File(s) Size is <b>" + Math.round(totalFileSize / 1024) + "</b> KB";
}
</script>
Routes of that form Post and Update API
app.post('/create/procedure', function (req, res) {
let proceduresinglefiles = req.files.procedurefiles
if(Array.isArray(proceduresinglefiles)==false){
console.log(Array.isArray(proceduresinglefiles));
console.log(typeof(proceduresinglefiles));
console.log(proceduresinglefiles);
var filename = proceduresinglefiles.name;
proceduresinglefiles.mv('./public/assets/documents/procedure/' + filename, function(err) {
if (err)
console.log(err);
});
var procedure = Procedure();
procedure.proceduretype = req.body.proceduretype;
procedure.procedurename = req.body.procedurename;
procedure.procedurenumber = req.body.procedurenumber;
procedure.scope = req.body.scope;
procedure.status = req.body.status;
procedure.forms = req.body.forms;
procedure.relatedprocedure = req.body.relatedprocedure;
procedure.norms = req.body.norms;
procedure.qualityrecords = req.body.qualityrecords;
procedure.expdate = req.body.expdate;
procedure.companyname = req.body.companyname;
procedure.version = req.body.version;
procedure.owner = req.body.owner;
procedure.approver = req.body.approver;
procedure.procedurefiles = filename;
procedure.flowchart = req.body.flowchart;
procedure.proceduredescription = req.body.proceduredescription;
procedure.isotags = req.body.isotags;
procedure.departmentname = req.body.departmentname
procedure.save(function (err, getprocedure) {
if (err) res.json(err);
else {
console.log(getprocedure);
res.redirect("/admin/view/procedure");
}
})
}
else
{
var filenamea=[];
for(var i=0;i<proceduresinglefiles.length;i++){
console.log(proceduresinglefiles.length);
console.log(i);
var procedurefilename = proceduresinglefiles[i].name;
console.log(procedurefilename);
filenamea[i]=procedurefilename;
console.log(filenamea);
proceduresinglefiles[i].mv('./public/assets/documents/procedure/' + procedurefilename, function(err) {
if (err)
console.log(err);
});
}
let multipleprocedurefilename= filenamea.toString();
var procedure = Procedure();
procedure.proceduretype = req.body.proceduretype;
procedure.procedurename = req.body.procedurename;
procedure.procedurenumber = req.body.procedurenumber;
procedure.scope = req.body.scope;
procedure.status = req.body.status;
procedure.forms = req.body.forms;
procedure.relatedprocedure = req.body.relatedprocedure;
procedure.norms = req.body.norms;
procedure.qualityrecords = req.body.qualityrecords;
procedure.expdate = req.body.expdate;
procedure.companyname = req.body.companyname;
procedure.version = req.body.version;
procedure.owner = req.body.owner;
procedure.approver = req.body.approver;
procedure.procedurefiles = multipleprocedurefilename;
procedure.flowchart = req.body.flowchart;
procedure.proceduredescription = req.body.proceduredescription;
procedure.isotags = req.body.isotags;
procedure.departmentname = req.body.departmentname
procedure.save(function (err, getprocedure) {
if (err) res.json(err);
else {
console.log(getprocedure);
res.redirect("/admin/view/procedure");
}
})
}
});
app.post('/edit/procedure/:id',(req, res) => {
Procedure.findOneAndUpdate({_id:req.params.id},{
$set:{
proceduretype : req.body.proceduretype,
procedurename : req.body.procedurename,
procedurenumber : req.body.procedurenumber,
scope : req.body.scope,
status : req.body.status,
forms : req.body.forms,
relatedprocedure : req.body.relatedprocedure,
norms : req.body.norms,
qualityrecords : req.body.qualityrecords,
expdate : req.body.expdate,
companyname : req.body.companyname,
version : req.body.version,
owner : req.body.owner,
approver : req.body.approver,
procedurefiles : req.body.procedurefiles,
flowchart : req.body.flowchart,
proceduredescription : req.body.proceduredescription,
isotags : req.body.isotags,
departmentname : req.body.departmentname
}},
{new: true, upsert:true},
function(err, procedurenew){
if(err){
console.log(err);
}
else
{
console.log(procedurenew);
res.redirect('/admin/view/procedure')
}
}
)
});
As far as I understand your problem, you need the old data before updating it to new one?
So you need to change(new:false) in your query API and your API code looks like:
app.post('/edit/procedure/:id',(req, res) => {
Procedure.findOneAndUpdate({_id:req.params.id},{
$set:{
proceduretype : req.body.proceduretype,
procedurename : req.body.procedurename,
procedurenumber : req.body.procedurenumber,
scope : req.body.scope,
status : req.body.status,
forms : req.body.forms,
relatedprocedure : req.body.relatedprocedure,
norms : req.body.norms,
qualityrecords : req.body.qualityrecords,
expdate : req.body.expdate,
companyname : req.body.companyname,
version : req.body.version,
owner : req.body.owner,
approver : req.body.approver,
procedurefiles : req.body.procedurefiles,
flowchart : req.body.flowchart,
proceduredescription : req.body.proceduredescription,
isotags : req.body.isotags,
departmentname : req.body.departmentname
}},
{new: false, upsert:true},
function(err, procedurenew){
if(err){
console.log(err);
}
else
{
console.log(procedurenew);
res.redirect('/admin/view/procedure')
}
}
)
});
[DO VOTE TO THIS ANSWER, IF ITS HELPFUL TO YOU]
I am trying to edit the record but I get the same result on clicking the edit button. Result of selected is not coming instead the first one is coming every time. I want to fetch the detail on clicking the edit button.
Getting result
If I click edit button of anyone it gets same value as above picture
router.js
router.get('/editCategory/:id', async (req,res,next) => {
const { id } = req.params;
const categories = await Category.findById({_id: id });
res.render('category', {
categories
});
res.json(data);
});
router.post('/editCategory/:id', async (req,res,next) => {
const { id } = req.params;
console.log(req.body);
const ctgy = await Category.findOne(id);
Object.assign(record, req.body);
await ctgy.save();
res.redirect('/category');
});
category.ejs
<tbody>
<% for(var i = 0; i <categories. length; i++) { %>
<tr>
<td><%= i+1 %></td>
<td><%= categories[i].category %></td>
<td><%= categories[i].status %></td>
<td>
<!-- Button trigger modal -->
<button type="button" class="btn bg-blue-w rounded edit" data-toggle="modal" data-target="#changecategoryModal">Edit</button>
<!-- Modal -->
<div class="modal fade" id="changecategoryModal" tabindex="-1" role="dialog" aria-labelledby="changecategoryModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="changecategoryModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="/edit/<%= categories[i]._id %>" method="post" enctype="multipart/form-data" id="categoryform">
<div class="form-group">
<label class="label-text">change Category</label>
<input type="text" class="form-control" placeholder="Category" name="category" value="<%= categories[i].category %>">
</div>
<div class="form-group">
<label class="label-text">Change image</label>
<input type="text" class="form-control" placeholder="Category" name="category" value="<%= categories[i].status %>">
<!-- <input type="file" name="myimage" value=""> -->
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<input type="submit" value="submit" class="btn bg-red rounded" form="categoryform">
</div>
</div>
</div>
</div>
</div>
Delete
</td>
</tr>
<% } %>
</tbody>
Error is in the below Line
const { id } = req.params;
when you are trying to destructor the req.params object , the value of id is not set. That is why query is returning the first row document every time.
Try to log the value of id and check.
in the second route
const ctgy = await Category.findOne(id);
the findOne accepts the object eg: Category.findOne({_id:id})
I want to take the input from the user and check the value of it whether it matches the value exists in firebase database or not.
I want to build a login component which provides the functionality of signUp user and signIn. I know it can be implemented by Auth but I want to use custom data. I was able to perform CRUD operations.enter image description here
This is login.component.ts where I want to implement the function
export class LoginComponent implements OnInit {
adminval: string;
passwordval : string;
newnew : string = 'employeeService.loginData.admin';
loginList : LoginID[];
constructor(private employeeService : EmployeeService, private router : Router) { }
ngOnInit() {
this.employeeService.getLoginData();
var x = this.employeeService.getLoginData();
x.snapshotChanges().subscribe(item =>{
this.loginList = [];
item.forEach(element => {
var y = element.payload.toJSON();
y["$key"] = element.key;
this.loginList.push(y as LoginID);
})
})
}
onEdit(emp : LoginID){
this.employeeService.loginData = Object.assign({}, emp);
}
onLogin(loginForm : NgForm){
if(this.adminval == this.employeeService.loginData.admin){
alert("OK");
}
else
alert("Not OK");
}
}
Here the login.component.html file code
<body style="background-color:#DD3247">
<div class="container" style="padding-top: 10%; padding-bottom: 8.1%;">
<div class="row justify-content-md-center">
<div class="col-md-5 login-box">
<h1 class="text-center login-text-color">Login</h1>
<hr>
<form #loginForm="ngForm">
<input type="hidden" name="$key" #$key="ngModel" [(ngModel)]="employeeService.loginData.$key">
<input type="hidden" name="admin" #admin="ngModel" [(ngModel)]="employeeService.loginData.admin" placeholder="Admin">
<input type="hidden" name="password" #password="ngModel" [(ngModel)]="employeeService.loginData.password" placeholder="Password">
<div class="form-row">
<div class="col-md-12">
<input type="text" class="form-control form-control-lg flat-input" name="adminvalue" #adminvalue="ngModel" [(ngModel)]="adminval" placeholder="Admin" required>
</div>
<div class="col-md-12">
<input type="password" class="form-control form-control-lg flat-input" name="passwordvalue" #passwordvalue="ngModel" [ngModel]="passwordval" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-lg btn-block btn-login" (click)="onLogin(loginForm)">Login</button>
</div>
</form>
</div>
</div>
</div>
<div class="container">
<div class="row justify-content-md-center">
<h6 class="text-center">Employee Register</h6><br>
<table class="table table-sm table-hover">
<tr *ngFor="let login of loginList">
<td>{{login.admin}}</td>
<td>{{login.password}}</td>
<td>
<a class="btn" (click)="onEdit(login)">
<i class="fa fa-pencil-square-o"></i>
</a>
<a class="btn">
<i class="fa fa-trash-o"></i>
</a>
</td>
</tr>
</table>
</div>
</div>
</body>
Somehow, I was able to do it by matching username value but by the wrong implementation. You can see there are 3 input hidden fields in the HTML file so first I have to click on the edit icon then that will insert the existing data into the hidden fields and then if the input from the adminval matches the one of the admin hidden field then it will show OK otherwise Not Ok.
I'm trying to parse a model from a form which contain a select(ngOptions) and save it to db but the selected value is never parsed. i'm stuck here can someone help please.
here is my code:
View
<section class="container" data-ng-controller="TagsController" >
<h2><i class="fa fa-pencil-square-o"></i>Add a new Tag</h2>
<form class="form-horizontal col-md-5" data-ng-submit="create()">
<div class="form-group ">
<div class="controls">
<input type="text" class="form-control input-lg" data-ng-model="label" id="label" placeholder="Label" required>
</div>
</div>
<div class="form-group" data-ng-controller="CategoriesController" data-ng-init="find()">
<select class="form-control input-lg" ng-model="category._id" ng-options="category._id as category.label for category in categories">
<option value="">Choose a Category</option>
</select>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn">
</div>
</div>
</form>
</section>
controller
angular.module('mean.tags').controller('TagsController', ['$scope', '$routeParams', '$location', 'Global', 'Tags', function ($scope, $routeParams, $location, Global, Tags) {
$scope.global = Global;
$scope.create = function() {
var tag = new Tags({
label: this.label,
category: this.category
});
tag.$save(function(response) {
$location.path("tags/");
});
this.label = "";
this.category = "";
};
...
I found the problem so i will answer my question. The problem was due to architecture restrictions, Angularjs don't allow to nest a ng-controller inside an other one...