posting data through angular form without page reload in angular - angularjs

$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.

Related

$broadcast is not working in Angularjs

I am using two controllers. When changes happen in one controllers it should get changed immediately in the other controller. I am using the $broadcast event to achive this.
My code:
My First controller
app.controller('configurationCtrl', function($scope, $http,Notification,$rootScope,$cookies) {
$scope.awssubmit=function(){
$scope.page_loader=true
$http.post("/insert_config_details",$scope.userdata).then(function(List){
if(List){
$scope.page_loader=false;
$cookies.put("bucket",$scope.userdata.bucket_name)
$scope.$broadcast('eventEmitedName', 'Some data');
Notification.success('<span class="glyphicon glyphicon-ok"></span> <strong>AWS Configuration details updated successfully.</strong>');
}
else{
$scope.page_loader=false;
Notification.error('<span class="glyphicon glyphicon-ok"></span> <strong>Error!!! Please try again later.</strong>');
}
$scope.awssave = false;
$scope.awstext=true;
})
}
});
My Second Controller:
app.controller('SidemenuController', function($scope, $http,$location,BucketService)
{
$scope.$on('eventEmitedName', function (event, data) {
console.log("Called"); //I am not getting this
value
console.log(data); // 'Some data' // I am not getting this
value
});
});
aws_submit() is called from my view and everything seems to work fine. But in SidemenuController I am not getting any data. Is there any mistake in my code?
Update:
My view :
<form id="awsform" method="post" name="awsform" class="form-horizontal" novalidate>
<div class="col-sm-6 four_module_config">
<div class="account_settings">
<div class="col-sm-12 heading_config" ng-hide="awssave">
<h4 class="sub_title col-sm-11" style="border-bottom:none">AWS S3 Configurations</h4>
<% if(valid_role[1]) { %>
<div class="action col-sm-1">
<span class="actico editrole" ng-click="editaws()">
<a href='javascript:void(0)' ></a>
</span>
</div>
<% } %>
</div>
<div class="col-sm-12 heading_config" ng-show="awssave">
<h4 class="sub_title col-sm-9" style="border-bottom:none">AWS S3 Configurations</h4>
<div class="action col-sm-3 close_config">
<button type="button" class="site_btn submit_btn save_config col-sm-2" id="submit" ng-show="awstest"
ng-click="verifyaws()">Test</button>
<button type="button" class="site_btn submit_btn save_config col-sm-2" id="submit" ng-show="submitawssave"
ng-click="awssubmit()">Submit</button>
<button type="button" class="site_btn submit_btn save_config col-sm-2" id="submit" ng-click="closeaws()">Cancel</button>
</div>
</div>
<div class="ipfield col-md-8 hint_txt_conf">
*Enter your AWS access Key, S3 Bucket name configured in your AWS Environment. Which is used to store your document in the
cloud.
</div>
<div class="ipfield first_ipfield">
<div class="col-md-8">
<label for="name" class="usrlabel">AWS access key <span class="mandat">*</span></label>
<input type="password" ng-disabled="awstext" ng-model="userdata.key" required name="key" class="txt_box" id="key" placeholder="Enter AWS access key">
<span toggle="#key" class="fa fa-fw fa-eye field_icon toggle-password"></span>
</div>
</div>
<div class="ipfield">
<div class="col-md-8">
<label for="name" class="usrlabel">AWS Secret Key <span class="mandat">*</span></label>
<input type="password" ng-disabled="awstext" ng-model="userdata.secretkey" required name="secretkey" class="txt_box" id="secretkey" placeholder="Enter AWS Secret Key">
<span toggle="#secretkey" class="fa fa-fw fa-eye field_icon toggle-password"></span>
</div>
</div>
<div class="ipfield">
<div class="col-md-8">
<label for="name" class="usrlabel">AWS Region Code <span class="mandat">*</span></label>
<input type="text" ng-disabled="awstext" ng-model="userdata.region" required name="region" class="txt_box" id="region" placeholder="Enter AWS Region Code">
</div>
</div>
<div class="ipfield">
<div class="col-md-8">
<label for="name" class="usrlabel">AWS Bucket Name <span class="mandat">*</span></label>
<input type="text" ng-disabled="awstext" ng-model="userdata.bucket_name" required name="bucket_name" class="txt_box" id="bucket"
placeholder="Enter AWS Bucket Name">
</div>
</div>
</div>
</div>
</form>
If you want to send data from one controller to another controller using $brodcast than use $rootscope.$broadcast
$rootScope.$broadcast('eventEmitedName', 'Some data');
Second Controller
app.controller('SidemenuController', function($scope, $http,$location,BucketService) {
$scope.$on('eventEmitedName', function (event, data) {
console.log("Called");
console.log(data); // 'Some data'
$scope.bucket = data;
});
});
Note: Do not use $rootscope.$on as listener because $rootscope
listener are not destroyed . Instead it will create listeners stack
If you want to call one controller event into another there are four methods available:
$rootScope.$broadcast() if your controller are not in a parent / child relation.
If your second controller (event fired here) is a parent you can use $scope.$broadcast();
If your second controller (event fired here) is a child you can use $scope.$emit();
The best way to solve this would be to use a service -> Example of using a service to share data between controllers.
Note: You need to destroy $rootScope.$on() listeners manually avoid stacking events. This Difference between $rootScope.$on vs $scope.$on and this Do you need to unbind $scope.$on in $scope $destroy event? will help you understand the basics of using events.
View
<div ng-controller="MyCtrl">
<button ng-click="broadcast()">
broadcast
</button>
</div>
<div ng-controller="MySecondCtrl">
{{ test }}
</div>
AngularJS application
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope, $rootScope) {
$scope.broadcast = function() {
$rootScope.$broadcast('test', 'testit');
}
});
myApp.controller('MySecondCtrl', function($scope, $rootScope) {
var registerScope = $rootScope.$on('test', function(test, args) {
console.log(args);
$scope.test = args;
});
// clean up, destroy event when controller get destroyed.
$scope.$on('$destroy', registerScope);
});
> demo fiddle

Issue with nested ng-controller in Angularjs

I am stuck with strange issue. Actually I am fetching the data from ajax and showing it on text boxes.
So, basically I have 3 text box (City, City1, City2). By default City textbox is visible rest will show if they have data from Ajax.
User can add city by clicking + button or remove by click on - button.
I am able to fetch and show the data properly on textboxes.
But when I want to add/show City1 or City by clicking on + button. It is simply executing form submit event.
Here is code for Ajax call.
formApp.controller('getprofile', function($scope,$http){
$http({
url: 'get_job_city.php',
method: "GET",
params: {uid: uid}
})
.success(function(data) {
if (data.success) {
$scope.formData.city1 = data.city1;
$scope.formData.city = data.city;
$scope.formData.city2 = data.city2;
}
});
})
Code for form save and show hide city textboxes.
var formApp = angular.module('formApp', []);
formApp.controller('formProfile1', function($scope,$http){
$scope.secondcity1city1 = false;
$scope.thirdcity2 = false;
$scope.hidecity1 = function() { $scope.secondcity1 = false; }
$scope.hidecity2 = function() { $scope.thirdcity2 = false; }
$scope.showcity = function() { $scope.secondcity1 = true; }
$scope.showcity1 = function() { $scope.thirdcity2 = true; }
$scope.formData = {};
$scope.formprofile1 = function() {
$scope.ajaxload = true;
var allData={'formData': $scope.formData, 'uid': uid}
$http({
method : 'POST',
url : 'city_update_exec.php',
data : allData,
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers
})
.success(function(data) {
$scope.ajaxload = false;
if (!data.success) {
$scope.errorcity = data.errors.city;
$scope.errorcity1 = data.errors.city1;
$scope.errorcity2 = data.errors.city2;
}else{
alert('City has been updated.');
}
});
};
})
HTML codes are below.
<div class="container" ng-controller="formProfile1">
<form name="formProfile1" method="post" id="formProfile1"
ng-submit="formprofile1()" role="form">
<div ng-controller ="getprofile">
<div id="firstcity">
<div class="col-xs-10">
<div class="topjob_resumetitle" ng-class="{ 'has-error' : errorcity }">
<input name="city" id="city" type="text"
class="form-control textbox1 txt-auto"
required="required" placeholder="Job Location* "
ng-model="formData.city">
<div class = "errorba" ng-show="errorcity">{{errorcity}}
</div>
</div>
</div>
<div class="col-xs-2">
<!--<button class="remove" ng-click="removeChoice()">-</button>-->
</div>
<button class="addfields" ng-click="showcity()">+</button><br>
</div>
<div ng-show="secondcity1">
<div class="col-xs-9"><div class="topjob_resumetitle" ng-class="{ 'has-error' : errorcity1 }">
<input name="city1" id="city1" type="text"
class="form-control textbox1 txt-auto"
placeholder="Job Location* " ng-model="formData.city1">
<div class = "errorba" ng-show="errorcity">{{errorcity1}}
</div>
</div>
</div>
<div class="col-xs-3">
<button class="remove" ng-click="hidecity1()">-</button>
<button class="addfields" ng-click="showcity1()">+</button><br>
</div>
</div>
<div ng-show="thirdcity2">
<div class="col-xs-10"><div class="topjob_resumetitle"
ng-class="{ 'has-error' : errorcity2 }">
<input name="city2" id="city2" type="text"
class="form-control textbox1 txt-auto"
placeholder="Job Location* "
ng-model="formData.city2">
<div class = "errorba" ng-show="errorcity2">{{errorcity2}}
</div>
</div>
</div>
<div class="col-xs-2">
<button class="remove" ng-click="hidecity2()">-</button>
</div>
More text boxes are here
</div>
The problem is that you have not set a type for your buttons, and therefore are defaulting to submit types, which will submit the first parent form found in the DOM when clicked. To allow your custom click handlers to execute properly, change your button types to "button" like so:
<button type="button" class="addfields" ng-click="showcity()">+</button><br>
Remove method="post" and add novalidate on form tag it will stop html5 validation
<form name="formProfile1" novalidate id="formProfile1"
ng-submit="formprofile1()" role="form">
Also if its still not works then change all your button to
<input type="button">//for rest of the buttons
<input type="submit">//for submit button
To make an http request you don't need to use the separate controller. Use factory method in your code for ajax and inject it as a dependency in your controller. Refer Angular Factory method

Save every scope from a Form in a service 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");
}

Error in ajax call using angular js

I am new to angular js .I tried making a small program that consists of ajax call using angular js $http .I guess I am some where wrong ,doing some mistake.
Would be happy If someone helps out. Following is code snippet
login.html
<head></head>
<body>
<form ng-app="" ng-controller="validateCtrl" name="myForm" novalidate>
<div ng-hide="var">
<h2><center>SIGN-IN</center></h2>
<p>Username:
<br>
<input type="text" name="user" ng-model="user" required><span style="color:red" ng-show="myForm.user.$error.required" />Username is required</p>
<p>Password:
<br>
<input type="password" name="password" ng-model="password" required /> <span style="color:red" ng-show="myForm.password.$error.required">Password is required.</span>
<p>
<input type="submit" ng-click="validate()" ng-disabled=" myForm.user.$invalid ||
myForm.password.$invalid" />
</p>
</div>
<div ng-hide="welcomeVar"> <span> {{ listOfCustomers }} </span>
<h2><center>Welcome! {{ user }}</center></h2>
<button class="list" ng-click="customerList()">List of Customers</button>
<ul>
<li ng-repeat="x in listOfCustomers">{{ x.CustomerID + ', ' + x.CompanyName }}</li>
</ul>
<br>
<button class="signout" ng-click="validate()">Log Out</button>
</div>
</form>
JS part:
<script>
function validateCtrl($scope, $http) {
$scope.user = 'ABC XYZ';
$scope.password = 'abcbc';
$scope.welcomeVar = true;
$scope.
var = false;
$scope.validate = function() {
$scope.
var = !$scope.
var;
$scope.welcomeVar = !$scope.welcomeVar
};
$scope.listOfCustomers = null;
$scope.customerList = function() {
$http.get("http://www.iNorthwind.com/Service1.svc/getAllCustomers")
.success(function(data) {
$scope.listOfCustomers = data;
})
.error(function(data) {
$scope.user = 'Xyz';
});
};
}
</script>
Your code is fine, except some syntax errors, but I hope it's because you tried to remove somrthing before posting code here ;)
Also the response for your request have this structure: {GetAllCustomersResult : [//here an array of elements]} , so, in success response handler you'll have to do: $scope.listOfCustomers = data.GetAllCustomersResult ;
But it's a minor things, the main issue described here:
AngularJS performs an OPTIONS HTTP request for a cross-origin resource
To debug this, you had to open developer tools in any browser('F12' is common key to open it), and look in console and network requests.

Use timer to timeout a form in AngularJs

I trying to build a feedback system with Angular. I am using angular ui router to route the user to different pages. It has basically 3 screens(see below).
Satisfied / Not satisfied links with icon.
A form for satisfied user to fill.
A form for unsatisfied user to fill.
I have succeeded in implementing it mostly. But am not able to figure out how to do 1 thing. I want to time out the form if some one leaves it without submitting it and send go back to the 1st screen, so next user can give feedback. But at the same time, I don't want give a flat timer as I don't want the form to redirect if someone is filling the form say slowly. So the timer should redirect to the form to first screen if no activity is happening. But the timer should reset each time the user interact with the form.
Routes:
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
// route to show main page with satisfied/unsatisfied
.state('main', {
url: '/main',
templateUrl: 'container.html',
controller: 'formController',
})
//satisfied
.state('main.happy', {
url: '/happy',
// data: { happy: true },
templateUrl: 'happy.html',
})
//not satisfied
.state('main.sad', {
url: '/sad',
templateUrl: 'welcome.html'
})
// catch all route
$urlRouterProvider.otherwise('/main');
})
The form code below:
<form id="signup-form" ng-submit="processForm()" >
<div class="col-md-12"><h4 class="col-md-12" >What made you satisfied</h4></div>
<div class="form-group col-md-12">
<div class="row">
<div class="radio col-md-6">
<label>
<input type="checkbox" ng-model="formData.option1" >
Option1
</label>
</div>
<div class="radio col-md-6">
<label>
<input type="checkbox" ng-model="formData.option2" >
Option2
</label>
</div>
</div>
</div>
<div class="col-md-12 contact">
<h4 class="col-md-12" >Want us to contact you?</h4>
<div class="form-group">
<div class="textbox col-md-12">
<label>Name </label>
<input type="text" ng-model="formData.name" >
</div>
<div class="textbox col-md-12">
<label>Email </label>
<input type="text" ng-model="formData.email" >
</div>
</div>
</div>
<div class="form-group row">
<div class="col-md-12 ">
<div class="col-md-12 contact">
<button type="submit" class="btn btn-primary" >Submit</button>
</div>
</div>
</div>
</form>
Here is a timeout function(you might could use $timeout as well) that I wrote to do something similar. It will allow the function to run for a set amount of time, and reset if a change has occurred to the scope of the timeout:
function TimeOut(fn, interval, scope, args) {
scope = scope || window;
var self = this;
var wrap = function() {
self.Clear();
fn.apply(scope, args || arguments);
};
this.Id = setTimeout(wrap, interval);
TimeOut.prototype.Id = null;
TimeOut.prototype.Cleared = false;
TimeOut.prototype.Clear = function() {
clearTimeout(this.Id);
this.Cleared = true;
this.Id = null;
}
}
I was using this to send some data to the server after a toggle is flipped, but I did not want it to fire if the user repeatedly flipped the switch. To Use this function you do something similar to this (Starting it on page load):
$scope.yourTimer = new TimeOut( SomeFunction($scope.someObject),
someInterval, yourScope, arg)
NOTE: I passed in window.parent for yourScope so the function will fire regardless if user left page. Yous do not need to pass in the args if you do not have any
Now what you need to do is add a watch/watchcollection to your form data and in this watch you do this:
$scope.$watchCollection( "yourData",
function( newValue, oldValue ) {
if(newValue != oldValue){
if(!($scope.youtTimer.Cleared === true && $scope.yourTimer === null){
$scope.yourTimer.Clear()
$scope.yourTimer = new TimeOut( SomeFunction($scope.someObject),
someInterval, yourScope, arg)
}else{
//recreate time just in case
$scope.yourTimer = new TimeOut( SomeFunction($scope.someObject),
someInterval, yourScope, arg)
}
}
}
);
Now if any thing changes in the "yourData", before the timer elapses, the current timeout is cleared and restarted again.

Resources