How to store data/parameters in html using angular? - javascript

If I have a comment thread, and I want to reply to the comment thread I would have to
return $http.post('/reply/', {
user: username,
test: text ,
parent: parent
}).then(registerSuccessFn, registerErrorFn);
The html would be something in the line of
<form role="form" ng-submit="vm.reply()">
<div class="form-group">
<label for="user">User</label>
<input type="text" class="form-control" id="user" ng-model="vm.user" placeholder="ex. john" />
</div>
<div class="form-group">
<label for="text">text</label>
<input type="text" class="form-control" id="text" ng-model="vm.text" placeholder="text" />
</div>
<div class="form-group">
<label for="parent">parent</label>
<input type="text" class="form-control" id="parent" ng-model="vm.parent" placeholder="parent" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
But the thing is that parent, and the user should be dynamically generated, how do I generate the form dynamically so that each form in html correctly stores the parameter for parent and user such that it reflect the parent of the post and user comment on it?

You can bind the page the form is on (or alternatively just the form itself) to a controller e.g. MyFormController. Then when initially loading the page/form, make sure to load the parent and user information and store in your $scope.vm model.
NB - I'm of course assuming that you have the parent and user information in your database since you said they will be dynamically generated.
var loadData = function () {
$http.get(user_url).success(function (user) {
$scope.vm.user = user;
});
$http.get(parent_url).success(function (parent) {
$scope.vm.parent = parent;
});
};
loadData();
That's about all you'll need to do and the data will be binded to your form.
Cheers

Related

How to use input field value attribute while using formControlName? [Angular]

What I want to achieve: I want pre-populated data in my form and I also want to use formControlName as I want the data too.
My html file -
<div class="container">
<p class="h4 my-5">Add New Result</p>
<div class="row">
<div class="col">
<form (ngSubmit)="editStudent()" [formGroup]="studentEditForm" name="myForm">
<div class="mb-3">
<label for="roll-no" class="form-label">Roll No.</label>
<input type="number" class="form-control" id="roll-no" name="rollno" formControlName="rollno" value="{{student.rollNo}}" placeholder="{{student.rollNo}}" autocomplete="off" required>
</div>
<div class="mb-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name" name="name" formControlName="name" value={{student.name}} required>
</div>
<div class="mb-3">
<label for="email" class="form-label">Email address</label>
<input type="email" class="form-control" id="email" name="email" formControlName="email" value={{student.email}} required>
</div>
<div class="mb-3">
<label for="score" class="form-label">Score</label>
<input type="number" class="form-control" id="score" name="score" formControlName="score" value={{student.score}} required>
</div>
<button type="submit" class="btn btn-primary" ng-click="submitForm(myForm.$valid)">Submit</button><button type="submit" class="btn btn-dark mx-4">Clear</button>
</form>
</div>
<div class="col"></div>
<div class="col"></div>
</div>
</div>
In Input Tag, I want to use value attribute so I can get a default value but I get Empty fields and I think it is because formControlName is controlling the data in my form. Is there a way to get pre-populated data using value attribute along with formControlName attribute?
Placeholder attribute works fine but I want a default value.
if you want a default value simply initialize the form with values, for example:
form = new FormGroup({
name: new FormControl('defaultNameValue'),
email: new FormControl('defaultEmailValue')
})
You should be doing it in you component instead of using value attribute. While defining the form example
studentEditForm= new FormGroup({
rollNo: new FormControl(this.student.rollNo)
})
or if student data is not available at the time of definition then use formcontrol.setValue after you initialize the student data something like
this.studentEditForm.controls.rollNo.setValue(this.student.rollNo)
Using the value and the CVA (Control Value Accessor: formControlName, formControl, and ngModel) to control the value of the input will override each other each time you change anyone of them.
Instead, it's better to rely only on one of them. If the CVA is used, then you can pass an initial value (default value) to the form-control while defining it:
studentEditForm = new FormGroup({
score: new FormControl(YOUR_INITIAL_VALUE),
});
For more info, check here how Angular passes the value from CVA to the value property when using both of them:
default_value_accessor.ts
Used value and CVA to control value
try this :
studentEditForm = new FormGroup({
score: new FormControl(VALUE),
});

Angular form is undefined when submitting via ngSubmit

I have a form outlined in my app.component.html file as below, when I click the Send button to submit the form I get an error in my Javascript saying that the chatForm is undefined.
I've had a look at a few different tutorials and I can't seem to find why this function is not operating as I expect. What am I doing wrong?
Also when I'm submitting the form how do I get the value of the input that is present in my form? I have a name of message defined on the form, how can I use this variable?
app.component.html
<div class="container">
<h2>Message Form</h2>
<form (ngSubmit)="sendMessage(chatForm)" #chatForm="ngForm">
<div>
<label for="message">Message</label>
<input type="text" id="message" name="message" [(ngModel)]="message" required>
</div>
<button type="submit" id="sendmessage" [disabled]="!chatForm.valid">
Send
</button>
</form>
</div>
app.component.ts
public sendMessage(form): void {
console.log("Message sent: " + form.value);
}
You should get the data by using
form.value.message
My example look like this
<form (ngSubmit)="onSubmit(registerForm)" #registerForm="ngForm">
<div class="form-group">
<label for="UserName">Your email</label>
<input
type="text"
ngModel
class="form-control"
id="UserName"
name="UserName"
required
/>
Then in my component I can access to the form data like this
onSubmit(formValue: NgForm) {
const registerModel: AccountModel = {
UserName: formValue.value.UserName,
Password: formValue.value.Password
};

passing data from Javascript to Laravel controller

I'm getting the error of MethodNotAllowedHttpException when I run the below code:
<h1>Temp Form</h1>
<form method="post" action="" role="form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="panel panel-default ">
<div class="container">
<div class="panel-body">
<div class="form-group">
<label for="firstName">First Name *</label>
<input name="fname" type="text" class="form-control" id="firstName" placeholder="Enter First Name" required>
</div>
<div class="form-group">
<label for="lastName">Last Name *</label>
<input name="lname" type="text" class="form-control" id="lastName" placeholder="Enter Last Name" required>
</div>
<div class="form-group">
<label for="qualification">Qualification *</label>
<input name="qualification" type="text" class="form-control" id="qualification" placeholder="BE, MCA, MBA Etc." required>
</div>
<div class="form-group">
<label for="emailAddress">Email address *</label>
<input name="email" type="email" class="form-control" id="emailAddress" placeholder="Enter Email" required>
</div>
<div class="form-group">
<label for="contactmessage">Message</label>
<textarea name="desc" type="text" class="form-control" id="contactmessage" placeholder="Message" rows="2"></textarea>
</div>
<input type="submit" id="add" class="btn btn-primary" onclick="addUpdateData(id)" value="Add"></button>
</div>
</div>
</div>
</form>
Code for routes.php :
Route::post('welcome/addupdate','FormController#addUpdateData');
code for controller :
public function addUpdateData(Request $req)
{
$id = $req->input('id');
if($id=="add")
{
$bs = new Basicusers;
$bs->fname = $req->fname;
$bs->lname = $req->lname;
$bs->qualification = $req->qualification;
$bs->email = $req->email;
$bs->desc = $req->desc;
$bs->save();
return "Data Successfully Added";
}
}
What I want is, when user clicks on add button, value in variable data add is passed, and on controller, I will check value for variable and if its add, than I will perform add operation.
meanwhile if the user click on edit button which is provided below in form, that row will be filled in form elements and the add button is changed to update button and value of variable data will be now update and I want to perform update operation...
I'm getting error when I am passing data using POST method
moreover I don't know how to get data passed using POST method..
for GET method I am using $id = Input::get('id'); method and its working
Here is JavaScript Function :
function addUpdateData(data) {
$(function() {
$.ajax({
method: "post",
url: "welcome/addupdate",
data: {
id: data
},
success: function(response) {
alert(response);
}
});
});
}
Try to use absolute path in your ajax request: url: "/welcome/addupdate"
Add a some ID for your form (ex. #form) and pass into the addUpdateData function serialized data from the form.
$('#add').on('click', function(e) {
e.preventDefault();
var data = $('#form').serialize();
addUpdateData(data);
});
Add also a input field as hidden type into the form which should have an ID of the existing resource. Then on the controller action you can get an array of the passed data and if if the ID of the resource exists the perform update. If not then create them.

How to $setdirty to a single input

I've got a little problem. I want to set to dirty a single input, I mean, because when I give a value automatically it stays in pristine class, doesn't change, and doesn't save the new value.
If I edit it, it works and change the class. I want to cancel that pristine class.
If anyone know please let me know.
<form class="form-horizontal" ng-repeat="studiant in studiants" name="form" id="form">
<input type="hidden" name="id" value="{{studiant.studiant_id}}" class="form-control" disabled>
<div class="form-group">
<label for="school" class="col-md-2 control-label">School</label>
<div class="col-md-1">
<input type="text" id="school" name="school" class="form-control" ng-init="studiant.school=studiant.studiant_school" ng-model="studiant.school">
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-2 control-label">Student's Name</label>
<div class="col-md-10">
<input type="text" id="name" name="name" class="form-control" ng-init="studiant.name=studiant.studiant_name" ng-model="studiant.name">
</div>
</div>
</form>
And the script:
document.getElementbyId('name').value = "anything";
Or, if I doing wrong and I have to change the value with ng-model or something, please help me.
http://plnkr.co/edit/bVoljJqiK3CLB2xqZ6Zm?p=preview
You can see a working example there.
Make sure you have the name attr set for the form and the input.
HTML Example:
<button id="dirty-button" ng-click="addText(); myForm.myText.$setDirty()">Make Dirty</button>
<hr>
<form name="myForm">
<input name="myText" id="myTextInput" type="text" ng-model="myText" required>
</form>
<br/>
<span ng-show="myForm.myText.$dirty">it's dirty now</span>
A simple function:
$scope.addText = function() {
$scope.myText = "now I'm dirty";
}
$scope.$on('$viewContentLoaded'){
$scope.form.fieldName.$dirty = true;
}
When your view is loaded then angular calls viewContentLoaded event is called. After that you can set the field dirty. And also if you want to call some method ,that should be executed after the content is loaded than you should call that method inside this $scope.$on('$viewContentLoaded'){..}
This should do the job
angular.element(document.querySelector('form')).scope().formname.fieldname.$setDirty()

Angularjs form not working

I have a form which inputs name of a country and then it overwrites a global variable. Submit button does nothing when clicked. Where am I missing?
Here is the HTML
<div ng-controller="InputController">
<form class="form-wrapper cf" role="form">
<input type="text" ng-model="model.country" placeholder="Search country..." required>
<button type="submit" ng-click="update()">Search</button>
<span>{{model.country}} ======</span>
</form>
</div>
And here is the controller.
LastFmApp.controller('InputController',
function InputController($scope) {
$scope.model = {};
$scope.update = function() {
console.log($scope.model.country);
};
});
I don't think it is an issue with angular js.
The submit button will reload the page so you won't be able to see changes in your model.
You can either use an input type button with ngClick:
<input type="button" ng-click="update()">Search</input >
Or an input type submit with ngSubmit attribute on your form:
<form ng-submit="update()">
<input type="submit">Search</input>
</form>
i dont think there is any issue with your code see your code is working in plunker
<div ng-controller="InputController">
<form class="form-wrapper cf" role="form">
<input type="text" ng-model="model.country" placeholder="Search country..." required>
<button type="submit" ng-click="update()">Search</button>
<span>{{model.country}} ======</span>
</form>
</div>
http://plnkr.co/edit/u9hqu1bASxxMgtEP1qAr?p=preview

Categories

Resources