Pull specific record from array using AngularJS - javascript

So I have created a SPA that displays student information from a database. I have function to add a student, display student data with specific views and update/delete student records.
I am struggling with the update function. My issue is that when I type a student ID into the search box on the page I cannot get it to pull that specific record from the JSON response from the server. I just can't seem to find the logic to write this correctly.
Here is part of my code, sorry if I have struggled to explain this properly. I could not find any other articles relating specifically to this issue I am having.
Here is the function I am using that is attached to the button on my HTML page, currently I just have it setup to pull the first record in the array (just to prove it will pull the data and fill the fields.
app.controller('editCtrl', function($scope, $http) {
$http.get("getStudentData.php")
.then(function (response) {
$scope.students = response.data;
});
$scope.getRecord = function() {
id = $scope.sid;
$scope.student = $scope.students[0];
And here is part of my HTML:
<div class="form-group">
<label for="sid">Student ID:</label>
<input type="text" class="form-control" id="sid" ng-model="sid">
</div>
<p><button type="button" class="btn btn-primary" ng-click="getRecord()">Get
Student Info</button> </p>
<div class='row'>
<div class="col-md-6">
<div class="form-group">
<label for="first_name">First Name:</label>
<input type="text" class="form-control" id="first_name" ng-
model="student.first_name">
</div>
<div class="form-group">
<label for="last_name">Last Name:</label>
<input type="text" class="form-control" id="last_name" ng-
model="student.last_name">

Pass the sid to your function as,
<p><button type="button" class="btn btn-primary" ng-click="getRecord(sid)">Get
Student Info</button> </p>
and then in controller, use array.find() to get the specific student
$scope.getRecord = function(sid) {
id = sid;
$scope.student = $scope.students.find(s=>s.id ==sid);
}

Related

HTML Form Not Displaying Correct Data in Handlebars View

I'm working with handlebars for the first time while creating an express app with sequelize and postgresql (courtesy of brad traversy). Upon filling out a form, I am using Joi for validating the request body , if there is an error I re-render the form (view) keeping the originally entered values. The problem is when this happens the text is being trimmed automatically.
E.G. I fill out the title field with "Hello World" and don't fill another field in the form, Joi won't be happy so I re-render the form (view) and when the title repopulates in the form, it will just say "Hello" instead.
Post Endpoint for Gig Resource
// Add a Gig
router.post("/add", (req, res) => {
let { title, technologies, budget, description, contact_email } = req.body;
const { error } = validateGig(req.body);
if (error) {
// Re-Render The Form
return res.status(400).render("add", {
error: error.details[0].message,
title,
technologies,
budget,
description,
contact_email
});
} else {
budget == "" ? (budget = "Unknown") : (budget = `$${budget}`);
// Make Lower Case and Remove Space After Comma
technologies = technologies.toLowerCase().replace(/, /g, ",");
// Insert Into Table
Gig.create({
title,
technologies,
budget,
description,
contact_email
})
.then((gig) => res.redirect("/gigs"))
.catch((err) => console.log("Error Adding Gig" + err));
}
});
Handlebars View
<section id="add" class="container">
<div class="form-wrap">
<h1>Add A Gig</h1>
<p>Your contact email will be shared with registered users to apply to your gig</p>
{{#if error}}
<div class="error">
<p>{{error}}</p>
</div>
{{/if}}
<form action="/gigs/add" method="POST">
<div class="input-group">
<label for="title">Gig Title</label>
<input type="text" name="title" id="title" class="input-box"
placeholder="eg. Small Wordpress website, React developer" maxlength="100" value={{title}}>
</div>
<div class="input-group">
<label for="technologies">Technologies Needed</label>
<input type="text" name="technologies" id="technologies" class="input-box"
placeholder="eg. javascript, react, PHP" maxlength="100" value={{technologies}}>
</div>
<div class="input-group">
<label for="budget">Budget (Leave blank for unknown)</label>
<input type="number" name="budget" id="budget" class="input-box" placeholder="eg. 500, 5000, 10000"
value={{budget}}>
</div>
<div class="input-group">
<label for="description">Gig Description</label>
<textarea name="description" id="description" class="input-box"
placeholder="Describe the details of the gig" rows="10">{{description}}</textarea>
</div>
<div class="input-group">
<label for="budget">Contact Email</label>
<input type="email" name="contact_email" id="contactemail" class="input-box"
placeholder="Enter an email" value={{contact_email}}>
</div>
<input type="submit" value="Add Gig" class="btn btn-reverse">
</form>
</div>
</section>
When using variables in your template, you'll still want to include the quotes around the attribute value.
For example:
value={{title}}
Should be written as
value="{{title}}"

AngularJs scope params undefined [duplicate]

This question already has answers here:
What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
(3 answers)
Closed 4 years ago.
I have just started learning AngularJS and I am trying to make this simple app with simple inputs, controllers and a firebase database.
Problem is, the $scope params userEmail and userPassword are always undefined in Signin() when I click the button.
HTML relevant code:
<body ng-app="indexApp">
...
<div class="row" ng-controller="loginCtrl">
<div class="hero-text-box">
<br>
<form>
<p class="p2"><label for="email">email</label></p>
<input ng-model="userEmail" id="email1" type="email"
name="email1" placeholder="email">
<p class="p2"><label for="password">pasword</label></p>
<input ng-model="userPassword" type="password" id="password"
name="password" placeholder="password" required>
<a class="btn btn-full" href="#" ng-click="Signin()">הכנס</a>
</form>
</div>
</div>
AngularJS javascript code:
var app = angular.module("indexApp", ["firebase"]); // using firebase
app.controller("loginCtrl", function($scope, $firebaseArray) // AngularJS
will auto add firebase
{
var ref = firebase.database().ref().child("users")
// create a synchronized array
$scope.users = $firebaseArray(ref)
$scope.Signin = function()
{
console.log($scope.userEmail) -- undefined!
....
If you want to use form with angularJS, you should follow angularjs form guide:https://docs.angularjs.org/guide/forms
In your case, you need to move signin() function to html form element.I created a jsfiddle based on your code: http://jsfiddle.net/sxwei123/ADukg/25254/
Hope this would help!
This might help
HTML
<body ng-app="indexApp">
...
<div class="row" ng-controller="loginCtrl">
<div class="hero-text-box">
<br>
<form>
<p class="p2"><label for="email">email</label></p>
<input ng-model="userdata.userEmail" id="email1" type="email"
name="email1" placeholder="email">
<p class="p2"><label for="password">pasword</label></p>
<input ng-model="userdata.userPassword" type="password" id="password"
name="password" placeholder="password" required>
<a class="btn btn-full" href="#" ng-click="Signin(userdata)">הכנס</a>
</form>
</div>
</div>
Controller
var app = angular.module("indexApp", ["firebase"]); // using firebase
app.controller("loginCtrl", function($scope, $firebaseArray) // AngularJS
will auto add firebase
{
var ref = firebase.database().ref().child("users")
// create a synchronized array
$scope.users = $firebaseArray(ref)
$scope.userdata = {};
$scope.Signin = function(data){
console.log(data) // you will get the object
}

How can I get value from cookie to put on an input "date"?

Being directly, I'm working on a project that have a filter button, but one of the requirements is to keep the parameters from the filter forms if the user refreshs the page.
The problem is: When I refresh the page with values into the form, just the DATE input resets
I have three forms, and the last is a Date. I managed to make it work for the first two with jQuery but with the date field it just does not work ...
Does anyone know how to solve it? thank you!
$(document).ready(function() {
if (document.getElementById("car_result"))
document.getElementById("car_result").value = localStorage.getItem("item_result");
if (document.getElementById("car_action"))
document.getElementById("car_action").value = localStorage.getItem("item_action");
if (document.getElementById("dei"))
document.getElementById("dei").value = localStorage.getItem("item_dei");
});
$(window).on('beforeunload', function() {
localStorage.setItem("item_result", document.getElementById("car_result").value);
localStorage.setItem("item_action", document.getElementById("car_action").value);
localStorage.setItem("item_dei", document.getElementById("dei").value);
});
<div class="container-fuid">
<div class="row col-sm-12">
<div class="col-sm-6">
<form class="form text-center" id="form1">
Result: <input id="car_result" type="text" class="form-control"><br>
Last name: <input id="car_action" type="text" class="form-control">
<input placeholder="Initial date" class="textbox-n form-control borderform" type="text" onfocus="(this.type='date')" name="dei" id="dei" /><br><br>
<button>Filter</button>
</form>
</div>
</div>
</div>

How to replicate input fields on click of button angular2

I'm facing the problem to replicate input fields onclick of a button
*I have few input fields and i can fill the data in that
*After filling the input fields i have a different data set to add so i need same fields.
*If i press button (addMore) the fields should replicate and it should allow me to add one more set of data.
*There should be one button(remove) that will help me to remonessessaryve those replicated fields if its not necessary.
I have tried this in angular ..and I'm sharing my sample code and plunker plz help me out
template.ts
<div class="card">
<input type="text" id="name" value="" class="form-control">
<label for="form1">Name</label>
<input type="text" id="mobile" value="" class="form-control">
<label for="form1">Mobile</label>
</div>
<button type="button" title="Add"class="btn btn-sm"
(click)="addMore">Add</button>
test.component.ts
export class App {
addMore() {
//function to replicate the form input fields
}
plunker link :- http://plnkr.co/edit/GCCnoMkLynpELwaYX11m?p=preview
You're looking for generating dynamic inputs using ngFor
You can initially create an array with initial value as follows,
inputelements = [{name: '',mobile:''}];
on click of addmore button you can push more elements and those will be rendered using ngFor
Template code will be,
<div class="card" *ngFor="let word of inputelements; let in=index" class="col-sm-3">
<div class="form-group">
<label for="form1">Name</label>
<input type="text" [(ngModel)]="inputelements[in].name" class="form-control" required>
<label for="form1">Mobile</label>
<input type="text" [(ngModel)]="inputelements[in].mobile" class="form-control" required>
</div>
</div>
<br>
<button type="button" title="Add"class="btn btn-sm pull-right"
(click)="addMore()">Add</button>
WORKING DEMO
Keep the track of the inputs with an array and add/remove with js :
inputs = [];
add() {
this.inputs.splice(0,0,this.inputs.length+1);
}
DEMO

How to set the value of an option when using ng-options in controller?

I am getting customer for given id,Customer details are name, email and type of customer {0,1}. For 0, customer will be Regular and 1 will Temporary.
I am able to show details of customer on form but but able to select the type of customer. My select options are showing {'regular', 'temporary'}, but not select any option value.
For example
customer1={'name':'john', 'email':'john#gmail.com', 'customer_type':0}
Form is able to show name and email but not selecting 'regular' options
Controller
$scope.customers_type=['regular','temporary'];
//I will get details of customer
$scope.customer=getCustomer($scope.id);
if($scope.customer.customer_type ==0)
$scope.customer.type=$scope.customers_type[0]
else
$scope.customer.type=$scope.customers_type[1]
HTML
<div>
<label for="Name">Name </label>
<input ng-model='customer.name' name="Name" type="text">
</div>
<div>
<label for="email">Email </label>
<input ng-model='customer.email' name="email" type="text">
</div>
<div>
<label for="enterprise">Type of type of Customer </label>
<select ng-model='customer.type' type="text" ng-options="type for type in customers_type">
</select>
</div>
Code is working fine without any error for angularjs 1.2.23
Just have replaced getCustomer method to object.
If it is not working then Check customer object using breakpoint and check whether it's proper or not and also check which version of angularjs you are using.
angular.module("myApp", []).controller('MyContrl', function($scope) {
$scope.customers_type = ['regular', 'temporary'];
//I will get details of customer
$scope.customer = {
'name': 'john',
'email': 'john#gmail.com',
'customer_type': 0
};
if ($scope.customer.customer_type === 0) {
$scope.customer.type = $scope.customers_type[0]
} else {
$scope.customer.type = $scope.customers_type[1]
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyContrl">
<div>
<label for="Name">Name</label>
<input ng-model='customer.name' name="Name" type="text">
</div>
<div>
<label for="email">Email</label>
<input ng-model='customer.email' name="email" type="text">
</div>
<div>
<label for="enterprise">Type of type of Customer</label>
<select ng-model='customer.type' type="text" ng-options="type for type in customers_type">
</select>
</div>
</div>
I think you need to specify ng-selected and set it to your current customer type.
If you don't specify ng-selected you'll end up with 3 options: '', 'regular', 'temporary'

Categories