How to reset form after submit in AngularJS - javascript

I am new to AngularJS and trying to do a project. I have a form which works perfectly. However, there is only one thing that I should do. After adding a customer, I need to clear the form. Because, when the user wants to add a second customer, tthe user sees the previously entered values.
$scope.add = function () {
$scope.loading = true;
$http.post('/api/Customer/', this.newcustomer).success(function (data) {
alert("Added Successfully!!");
$scope.addMode = false;
$scope.customers.push(data);
$scope.loading = false;
}).error(function (data) {
$scope.error = "An Error has occured while Adding Customer! " + data;
$scope.loading = false;
});
};

Try this:
$scope.add = function () {
$scope.loading = true;
$http.post('/api/Customer/', this.newcustomer).success(function (data) {
alert("Added Successfully!!");
$scope.addMode = false;
$scope.customers.push(data);
$scope.loading = false;
this.newcustomer = {};
}).error(function (data) {
$scope.error = "An Error has occured while Adding Customer! " + data;
$scope.loading = false;
});
};

You have to manually clear the values of the form elements
This should do it:
delete $scope.newcustomer

Related

Loading spinner (ng-show = loading) always true after form submission. Need to make it false after receiving data

I am having problem with scope variable. I initiate the loading spinner by setting ng-show property to true, as soon someone clicks the submit button on my contact form. After that, I send form data to my back end and after processing I should be able to set the loading spinners ng-show property to false. However the property is not chaging to false after receiving data from backend.
here is my code.
$scope.submit = function(){
$scope.loading = true; //at this point loading spinner appears
//pass them to api that handles mail sending and
var contact_name = $('#name').val();
var contact_email = $('#email').val();
//var contact_body = $('#contact_body').html();
console.log(contact_name +" " +contact_email );
if(contact_name != "" && contact_email != "")
{
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: baseUrl+'api/mail',
type:'POST',
dataType:'json',
data: $('#contactFormId').serialize(),
success:function(data)
{
$scope.loading = false;
console.log("1: Scope loading is set to "+ $scope.loading);
if(data)
{
$('.msgHolder').css({
'border':'1px solid #9e9c9c',
'text-align':'center',
'padding':'8px',
'color':'green'
});
$('.msgHolder').html(data.message);
$scope.loading = false;
console.log("2 Scope loading is set to "+ $scope.loading); //this is the PROBLEM, conse says $scope.loading is false but the spinner does not go away.
}
else
{
//default bg
$('.msgHolder').css({
'border':'1px solid #9e9c9c',
'text-align':'center',
'padding':'8px',
'color':'red'
});
$('.msgHolder').html("Email Was not sent. There was an Error.");
vcRecaptchaService.reload($scope.widgetId)
}
}
});
}
else
{
$scope.loading = false;
console.log("2: Scope loading is set to "+ $scope.loading); // this actually works. and spinner disappears
$('.msgHolder').css({
'border':'1px solid #9e9c9c',
'text-align':'center',
'padding':'8px',
'color':'red'
});
$('.msgHolder').html("Email Was not sent. Required data missing");
}
}
You should use the $http service that Angular provides. Otherwise you'll have to tell Angular yourself that the data has changed:
$scope.$apply(function() {
$scope.loading = false;
});
By the way, you seem to be doing a lot of things that are not really the Angular way (touching the DOM, for example). Is there a reason?

How to avoid data mix between $scope variables in ng-repeat when it is broadcasted in other controller?

I have two controllers. In one controller I am storing the data in scope variable for different categories and for different weeks and days. Here is the function for the same:
$scope.fetchWeekList = function(type) {
$scope.loading = true;
var paramtype = (type == 'mo')?'Mobiles':((type == 'ta')?'Tablets':((type == 'la')?'Laptops':'TVs'));
var weekListUrl = url + "/" + paramtype;
var request = $http({
method: "GET",
url: weekListUrl,
headers: { 'Accept' :'application/json','Content-Type' :'application/json', 'Accept-Language': 'en'}
});
request.success(
function(data) {
$scope.weekList = data.object;
$scope.loading = false;
});
request.error(
function(data, status) {
console.log(status);
$scope.weekList = data || "Request failed";
$scope.loading = false;
});
};
Please pat attention that I am fetching the data for the week lists for all the categories with this single function.
Then I am using this:
$scope.$on('fetchSaleDetails', function(event,type) {
$scope.fetchWeekList(type);
}
Then I am broadcasting it in the other controller like this:
$rootScope.$broadcast('fecthSaleDetails','mo');
$rootScope.$broadcast('fecthSaleDetails','ta');
$rootScope.$broadcast('fecthSaleDetails','la');
But when I switch the company the weeks of one category appears in the other and when I click again on the company the data changes. This is the function to update company.
$scope.updateCom = function(corresCom) {
$("html, body").animate({scrollTop: 0 }, "slow");
$rootScope.$broadcast('updateComDetail',corresCom);
$rootScope.$emit('fetchSaleDetails','mo');
$rootScope.$broadcast('fecthSaleDetails','mo');
$rootScope.$broadcast('fecthSaleDetails','ta');
$rootScope.$broadcast('fecthSaleDetails','la');
$scope.selectedCom = corresCom;
};
I would be grateful if someone can tell me the issue here. I have tried my best but no luck.
Thanks.

ng-repeat update after build

I have a list of events that gets build from a JSON call to my server. The list gets parsed through ng-repeat. I want to implement a like button for the event and if its liked, replace that with unlike.
<a ng-show='event.liked==null' ng-click="like(event.event_id)">Like</a>
<a ng-show='event.liked!=null' ng-click="unLike(event.event_id)">Unlike</a>
Everything works perfectly except I have to refresh the feed to show "Unlike". Is there a way I can update the specific list item at the index that was liked once clicked without the need to refresh.
Please let me know if you need more information. Thanks!
edit: adding like function & unlike function. All it does is send request to my server to like or unlike a specific event with the event_id and user token.
$scope.like = function (event_id) {
var url = www.server.com?type=unlike&event_id=...
$http.post(url).success(function (data) {
console.log('success like');
//I want it to update my index here
}).error(function (data) {
console.log('fail like');
});
};
$scope.unLike = function (event_id) {
var url = www.server.com?type=unlike&event_id=...
$http.post(url).success(function (data) {
console.log('success unlike');
//I want it to update my index here
}).error(function (data) {
console.log('fail unlike');
});
};
Instead of passing in the event_id, pass the object to the like and unLike functions and update the object in success handler.
HTML
<a ng-hide='event.liked' ng-click="like(event)">Like</a>
<a ng-show='event.liked' ng-click="unLike(event)">Unlike</a>
Controller
$scope.like = function(event) {
var url = 'www.server.com?type=unlike&event_id=' + event.event_id;
$http.post(url).success(function (data) {
event.liked = true;
console.log('success like');
}).error(function (data) {
console.log('fail like');
});
};
$scope.unLike = function(event) {
var url = 'www.server.com?type=unlike&event_id=' + event.event_id;
$http.post(url).success(function (data) {
event.liked = null;
console.log('success unlike');
}).error(function (data) {
console.log('fail unlike');
});
};

ng-class only for current scope in ng-repeat angularjs

I'm having trouble with the ng-class part of AngularJS.
The only thing I figured out was adding the class after a success or error to allll buttons where the ng-click was on.
But I only want to add/change the class of the currently clicked element. Is that even possible in a way?
<section ng-repeat="user in users">
<button class="btn" ng-click="myFunction(user);" ng-class="{invalid:errors,done:success}"></button>
</section>
<script>
function UsersController($scope, $http) {
$http.get('/users.json').success(function(users) {
$scope.users = users;
$scope.errors = false;
$scope.success = false;
});
$scope.myFunction = function(user) {
$http.post('/myUrl/'+user.id, student)
.success(function(data, status, headers, config) {
// $scope.success = true;
user.success = true;
})
.error(function(data, status, headers, config) {
// $scope.errors = true;
user.errors = true;
});
}
}
</script>
What I want is just the current scope, but that doesn't work.
My function does work, except for passing the ng-class values trough.
Another solution:
<section ng-repeat="user in users">
<button class="btn" ng-click="myFunction(user)"
ng-class="{invalid: isInvalid(user), done: isSuccess(user)}">{{user.name}}</button>
</section>
So you create isInvalid and isSuccess functions and pass in current user object:
$scope.isSuccess = function(user) {
return user === $scope.state.success;
};
$scope.isInvalid = function(user) {
return user === $scope.state.errors;
};
These two functions can decide if current user is invalid or successful. For example when there is an error you set it like this:
$scope.state = {
success: false,
errors: user
};
Demo: http://plnkr.co/edit/RDJy9VsRkhAO0cFnb6AV?p=preview
Have a property on the scope to represent the current user and a test for it in the ng-class expression:
$scope.currentUser = null;
$scope.myFunction = function(user) {
$http.post('/myUrl/'+user.id, student)
.success(function(data, status, headers, config) {
$scope.currentUser = user;
user.success = true;
})
.error(function(data, status, headers, config) {
user.errors = true;
});
};
ng-class="{invalid:user.errors && currentUser == user,done:user.success && currentUser == user}"
Instead of attaching the function myFunction to the $scope, you want to attach it to each user as such...
for(var i=0;i<users.length;i++){
users[i].myFunction= function(id){...}
}
and then for your ng-class you do.
ng-class={invalid: user.errors, done:user.success}

Is there a way to prevent submitting a form with this javascript/jquery?

I have searched the net, i´ve tried implementing "preventdefaults" and "return false" statements all over the place, but I can´t seem to find a way to prevent this form submitting and reloading the page. It only reloads when the form has been validated. I´m kind of a beginner, but I really tried hard achieving the script to validate a form (which has "post"-method and "#" as action), and make an ajax-call. It´s a school assignment and would be graceful towards any pointers you guys could give.
$(document).ready(function()
{
$("#submit").click(function()
{
var gbname = $("#gbname")[0];
var gbmessage = $("#gbmessage")[0];
formFields = [gbname, gbmessage]
var warning = false;
for (i=0; i<formFields.length; i++)
{
formFields[i].style.backgroundColor = "white";
if (formFields[i].value == "")
{
formFields[i].style.backgroundColor = "red"
$(formFields[i]).bind("keyup", resetBgColor);
$(formFields[i]).bind("change", resetBgColor);
warning = true;
}
}
if (warning == true)
{
alert("Vänligen fyll i fälten korrekt!");
return false;
}
else
{
$.post('ajax.php', {gbname: gbname, gbmessage: gbmessage},
function(data)
{
$("#successmessage").html(data);
$("#successmessage").hide();
$("#successmessage").fadeIn(1500); //Fade in error/success-meddelande
var comment = $("<div class='film2'><p class='names'><b>Namn:</b>" +gbname+ "</p> <p class='messages'><b>Meddelande:</b>" +gbmessage+ "</p></div>");
$("#kommentarer").prepend(comment);
clearForm();
});
return false;
}
return false;
});
});
Your references to the input elements as objects and the data returned from your AJAX call were a bit muddled.
Also incorporated the suggestion of binding to the form's submit event. DEMO
$(document).ready(function () {
function clearForm(){
$('input.reset').each(function(){
$(this).val('');
});
}
$("form").on('submit', function () {
alert('submitted!');
var gbname = $("#gbname");
var gbmessage = $("#gbmessage");
formFields = [gbname[0], gbmessage[0]]
var warning = false;
for (i = 0; i < formFields.length; i++) {
formFields[i].style.backgroundColor = "white";
if (formFields[i].value == "") {
formFields[i].style.backgroundColor = "red"
$(formFields[i]).bind("keyup", resetBgColor);
$(formFields[i]).bind("change", resetBgColor);
warning = true;
}
}
if (warning == true) {
alert("Vänligen fyll i fälten korrekt!");
return false;
} else {
var J = JSON.stringify({
"gbname": gbname.val(),
"gbmessage": gbmessage.val()
});
console.log(J);
$.ajax({
type: "POST",
url: '/echo/json/',
datatype: 'json',
data: {
json: J,
delay: 3
},
success: function (data) {
$("#successmessage").html(data);
$("#successmessage").hide();
$("#successmessage").fadeIn(1500); //Fade in error/success-meddelande
var comment = $("<div class='film2'><p class='names'><b>Namn:</b>" + data.gbname + "</p> <p class='messages'><b>Meddelande:</b>" + data.gbmessage + "</p></div>");
$("#kommentarer").prepend(comment);
clearForm();
} // end success
}); // end ajax
return false;
} // end else
return false;
});
});
I suggest using
$("form").on('submit', function (e) {
[...]
if(validationErrors) {
alert(Errormessage);
e.preventDefault();
}
[...]
instead of returning false.
https://developer.mozilla.org/en-US/docs/DOM/event.preventDefault
In order to get it to work, you have to use the event as a parameter of your callback function.

Categories

Resources