Save every scope from a Form in a service Angularjs - angularjs

I would like to save my datas from my form to my service function setData(), but I am not sure how to do it. I have already done the service, the setData() function, and my form.
Form
<form id="eventForm" data-toggle="validator" class="text-left" role="form" name="form.eventForm">
<div class="form-group col-md-12">
<input type="text" ng-model="form.return" name="RT" id="return"> Return
<input type="text" ng-model="form.oneway" name="OW" id="oneway"> One way
</div>
<button name="submit" class="btn btn-default ng-click="form.$valid && submit()">Pay now</button>
</form>
AngularJS submit method
$scope.submit = function() {
FormData.setData($scope.form);
$location.path("/flights");
}
Service setData()
this.data = JSON.parse(sessionStorage.getItem("flights") || '{}');
this.setData = function(data) {
this.data = data;
sessionStorage.setItem("flights", JSON.stringify(data));
}
this.getData = function() {
return this.data;
}
I don't know how should I pass my whole data from my Form to setData() function.

Try changing the submit button to disable on an invalid form, and set the submit action to send the form object. Then, in the controller, set the function to accept an argument (the form data), and use that.
HTML
<form id="eventForm" data-toggle="validator" class="text-left" role="form" name="form.eventForm">
<div class="form-group col-md-12">
<input type="text" ng-model="form.return" name="RT" id="return"> Return
<input type="text" ng-model="form.oneway" name="OW" id="oneway"> One way
</div>
<button name="submit"
class="btn btn-default
ng-disabled="form.$invalid"
ng-click="submit(form)">
Pay no
</button>
</form>
JS
$scope.submit = function(submitData) {
FormData.setData(submitData);
$location.path("/flights");
}

Related

posting data through angular form without page reload in angular

$scope.createPermission= function(form){
AppFactory.createNewPermission(form)
.success(function(data) {
$scope.updatedPermissions = data;
$scope.navMode='getPermission'
var original = $scope.permission;
$scope.reset(original);
$scope.permission = {}; // clear the form
})
.error(function(data) {
console.log('Error in creating permission: ' + data);
});
$scope.Execute=function(id) {
if($scope.navMode=='updatePermission') {
$scope.editPermission(id);
} else if($scope.navMode=='createPermission') {
$scope.createPermission($scope.permission);
}
}
}
$scope.reset= function(original) {
$scope.permission= angular.copy(original)
$scope.form2.$setPristine(true);
//$scope.form2.$setUntouched(true);
}
HTML:
<div class="row">
<div class="container col-sm-6 col-sm-offset-2"
ng-show="navMode == 'createPermission' || navMode=='updatePermission' || navMode=='getPermission'">
<div>
<h1>Permissions</h1>
</div>
</div>
<form class="form2" ng-show="showHide('Create')" ng-if=""name="form2" ng-submit="Execute(permissionId)" novalidate>
<div class="form-group" ng-class="{ 'has-success': form2.name.$valid && submitted, 'has-error': form2.name.$invalid && submitted }">
<label>Permission Name</label>
<input type="text" name="name" class="form-control" ng-model="permission.name" required/>
<p class="help-block" ng-show="form2.name.$error.required && submitted">
A permission name is required
</p>
</div>
<div class="row col-lg-offset-3">
<button class="btn btn-primary" ng-disabled="form2.$invalid" type="submit">Save</button>
</div>
</form>
</div>
I have above piece of code in controller and is executed on submission of the form. Now , It does work fine on page reload but I can not add data through form back to back. I need to reload teh page everytime to post new data through the form.
Why exactly is that ?
How do I fix this?
Without seeing the HTML part of this, I would guess you are using the action attribute of <form>. AngularJS provides ng-submit which allows you to set a handler for the submit event, without actually 'submitting' the form in the traditional sense. See https://docs.angularjs.org/api/ng/directive/ngSubmit.

Cannot read property $valid of undefined

I have a form like this -
<form name="myForm" novalidate>
There are some fields in the form which I am validating and then submitting the form like this -
<input type="button" ng-click="Save(data)" value="Save">
In the controller, I want to check if the form is not valid then Save() should show some error on the page. For that, I am setting up a watch like this -
$scope.$watch('myForm.$valid', function(validity) {
if(validity == false)
// show errors
});
But I am always getting this error on running it -
Cannot read property '$valid' of undefined
Can someone explain why?
Thanks
You just misspelled "myForm" in your controller code. In order to remove the error, Write "myform" instead of "myForm".
However I expect what you want is like this.
$scope.Save = function(data){
alert($scope.myform.$valid);
}
I setup jsfiddle.
In my case I was wrapping the form in a modal created in the controller and therefore got the same error. I fixed it with:
HTML
<form name="form.editAddress" ng-submit="save()">
<div class="form-group">
<label for="street">Street</label>
<input name="street" type="text" class="form-control" id="street" placeholder="Street..." ng-model="Address.Street" required ng-minlength="2" />
<div class="error" ng-show="form.editAddress.street.$invalid">
<!-- errors... -->
</div>
</div>
<button type="submit" class="btn btn-primary" >Save address</button>
</form>
JS
angular.module("app").controller("addressController", function ($scope, $uibModal, service) {
$scope.Address = {};
$scope.form = {};
$scope.save = function() {
if (modalInstance !== null) {
if (isValidForm()) {
modalInstance.close($scope.Address);
}
}
};
var isValidForm = function () {
return $scope.form.editAddress.$valid;
}
});

Adding hidden form field to array in Angular

I am trying to add a "hidden" field to a basic form in Angular (using Firebase as the backend). I'm having trouble figuring out how to include this field as part of the array when the form is submitted. I want to include {type: 'Basic'} as part of the array. I've looked at the other related posts on this site, but am still unsure how to apply to my particular situation.
Any suggestions on how to do this?
Javascript:
myApp.controller('NewProjectCtrl', function ($location, Projects) {
var editProject = this;
editProject.type = 'Basic'; //this is the hidden field
editProject.save = function () {
Projects.$add(editProject.project).then(function(data) {
$location.path('/');
});
};
});
HTML:
<form>
<div class="control-group form-group">
<label>Name</label>
<input type="text" name="name" ng-model="editProject.project.name">
</div>
<label>Description</label>
<textarea name="description" class="form-control" ng-model="editProject.project.description"></textarea>
<button ng-click="editProject.save()" class="btn btn-primary">Save</button>
</form>
You don't need a hidden form field, just submit your value in your controller like this:
editProject.save = function () {
editProject.project.type = 'Basic';
Projects.$add(editProject.project).then(function(data) {
$location.path('/');
});
};
All attributes of your editProject.project will be submitted, as you may notice in the developer console.
I would structure the controller a bit different.. here is an example (I am considering you are using angular-resource, where Projects returns a Resource?):
myApp.controller('NewProjectCtrl', function ($location, Projects) {
$scope.project = new Projects({type: 'Basic'});
$scope.save = function () {
$scope.project.$save().then(function(data) {
$location.path('/');
});
};
});
<form ng-submit="save()">
<div class="control-group form-group">
<label>Name</label>
<input type="text" name="name" ng-model="project.name">
</div>
<label>Description</label>
<textarea name="description" class="form-control" ng-model="project.description"></textarea>
<input type="submit" value="Save" class="btn btn-primary" />
</form>
The save function will $save the new project resource (this is an default method and will make a POST on the given resource URL).

Input text not being cleared out

I'm trying to clear an input text after saving some data but it just doesn't work. This is what I've tried so far (what it's in comments too):
Thanks in advance for any help!
HTML:
<div id="add-tag">
<h3>Add new tag</h3>
<form name="addTagForm">
<input class="form-control" type="text" ng-model="newTag" ng-change="onChangeTag()">
<button class="btn btn-primary" ng-click="addTag(newTag)">Add Tag</button>
</form>
</div>
JS:
//$scope.master = {};
// Reset scope
$scope.reset = function() {
$scope.newTag = "";
//$scope.newTag = angular.copy($scope.master);
};
$scope.addTag = function(tag) {
// Save some data (this works fine)
// ....
// Reset input field
$scope.reset();
};
UPDATE:
My ng-controller was set to the parent template (I'm using ui.router). Just added it to the child template and it indeed worked.
<div id="add-tag" ng-controller="FormController">
<h3>Add new tag</h3>
<form name="addTagForm">
<input class="form-control" type="text" ng-model="newTag" ng-change="onChangeTag()">
<button class="btn btn-primary" ng-click="addTag(newTag)">Add Tag</button>
</form>
</div>
I am new in angularjs but after trying some thing i got some sort of solution for you. You can check this bin. I have just added a controller :-
function test_c($scope){
$scope.reset = function() {
$scope.newTag = "";
//$scope.newTag = angular.copy($scope.master);
};
$scope.addTag = function(tag) {
// Save some data (this works fine)
// ....
// Reset input field
$scope.reset();
};}
Look at the html part:-
<body ng-app>
<div id="add-tag" ng-controller="test_c">
<h3>Add new tag</h3>
<form name="addTagForm">
<input class="form-control" type="text" ng-model="newTag" ng-change="onChangeTag()">
<button class="btn btn-primary" ng-click="addTag(newTag)">Add Tag</button>
</form>
</div>

How To save users feed data in database in my custom form in WordPress?

I have created a custom form in my project and also create mail functionality for it. Now i want to save all the data post by users in database how do i achieve it?
Here is my Form:
<form id="formMy">
<input name="txtFirstName" type="text" required placeholder="Name" id="txtFirstName">
<input name="PopupContact_email" type="email" required placeholder="E-Mail Address" id="requestemail">
<input name="txtOrganisationName" type="text" required placeholder="Company/ Institute Name" id="requestcompany">
<input type="hidden" name="hiddenform">
<button class="btn btn-primary btn-lg bbtn" data-toggle="modal" data-target="#myModal" style="display:none;">
Launch demo modal
</button>
<button type="button" class="btn btn-inverse" style="vertical-align:top;" name="submit" onClick="ajaxFormSubmit2();">Request a Demo</button>
</form>
And this is my ajax code:
<script>
function ajaxFormSubmit2(){
var txtFirstName = jQuery('#txtFirstName').val();
var requestemail = jQuery('#requestemail').val();
var requestcompany = jQuery('#requestcompany').val();
var atpos=requestemail.indexOf("#");
var dotpos=requestemail.lastIndexOf(".");
if(txtFirstName=="" || requestemail=="" || requestcompany==""){
jQuery('.alertred').show();
jQuery(".alertred").delay(10000).hide(0);
jQuery('.alertred').html('<strong>Error!</strong> Please Fill out all the fields.');
return false;
}
else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=requestemail.length)
{
jQuery('.alertred').show();
return false;
}
else
{
jQuery.post("<?php echo get_bloginfo('template_directory').'/mail2.php'; ?>",{txtFirstName:txtFirstName,requestemail:requestemail,requestcompany:requestcompany},function(r){
if(r=="success"){
jQuery('.success').show();
}
});
}
}
</script>
You can get all the form data using formId_specifier.serialize() method. And you get this in your php file like this one example for you.
JS Code::
$(document).on('submit', 'form#form_id',function(){
$.post(
MyAjax.ajax_url,{
action: AJAX_FILE_URL,
data: me.serialize()
}, function(response){
// Handle after getting response
}
);
});
In php code you can get form date using this code:
parsestr($_POST['data'], $form_data); // now all form data is assign to $form_data

Resources