form does not submit when using ng-click - javascript

I have a simple form which need to submit when click button and hide stuff with ng-click, it does submit the form when I don't add the ng-click for the hide stuff purpose, when I add the ng-click the form don't submit:
the form head :
<form class="form" name="form" ng-submit="edit(form)" novalidate ng-show="editorEnabledView">
the button :
<button analytics-on analytics-event="Bouton Terminer" analytics-category="Profil" ng-click="disableEdditing()" class="btn btn-lg btn-primary" type="submit">{{ step == 2 ? 'Terminer' : 'Enregistrer' }}</button>
CTRL
$scope.editorEnabledView = false;
$scope.showEdditing = function () {
$scope.editorEnabledView = true;
console.log("YES TRUE");
}
$scope.disableEdditing = function () {
$scope.editorEnabledView = false;
}
my edit function :
$scope.edit = function (form) {
if (!form.$valid) return;
$scope.errors = {};
if (!$scope.address.input) $scope.errors.address = 'Votre adresse de travail est obligatoire.';
var data = {
gender: $scope.user.gender,
name: {
first: $scope.user.name.first,
last: $scope.user.name.last
},
phone: $scope.user.phone,
job: {
name: $scope.user.job.name,
status: $scope.user.job.status
},
about: $scope.user.about,
interests: $scope.user.interests
};
getAddress(function (response) {
data.address = {
full: response.formatted_address,
city: getCity(response.address_components),
latitude: response.geometry.location.lat(),
longitude: response.geometry.location.lng(),
timestamp: new Date()
};
User.update(data, function (user) {
submit = true;
Auth.update(user);
if ($scope.step == 1) return $scope.step++;
$location.path($scope.step == 2 ? '/' : '/users/view/' + user._id);
}, function (err) {
Auth.update(originalUser);
$scope.user = originalUser;
angular.forEach(err.data.errors, function (error, field) {
$scope.errors[field] = error.message;
});
});
});
//$scope.editorEnabledView = false;
};
I discovered that when go to another page and come back to the user profile I see that the form get submitted !! but I want to see it after the submit

I had to change my answer cause now its clear that all you want to do is to hide your form after submit. This can be done with the use of form.$submitted and ng-hide
<div ng-controller="MyCtrl">
<form class="form" name="form" ng-submit="edit(form)" ng-hide="form.$submitted" ng-show="!form.$submitted" novalidate >
</div>
<button analytics-on analytics-event="Bouton Terminer" analytics-category="Profil" class="btn btn-lg btn-primary" type="submit">{{ step == 2 ? 'Terminer' : 'Enregistrer' }}</button>

I did a snippet and everything seems to be working... I think you are doing something wrong. Maybe you are missing the ng-submit in the form tag. See my snippet and change your code.
var $scope = {};
var myApp = angular.module('myApp', []);
myApp.controller('ngSubmitCtrl', ['$scope', function($scope){
$scope.editorEnabledView = true;
$scope.showEdditing = function () {
$scope.editorEnabledView = true;
alert("showEdditing");
}
$scope.disableEdditing = function () {
$scope.editorEnabledView = false;
alert("disableEdditing");
}
$scope.edit = function (form) {
alert("submitForm");
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp' ng-controller="ngSubmitCtrl">
<form class="form" name="form" ng-submit="edit(form)" novalidate ng-show="editorEnabledView">
<button
analytics-on analytics-event="Bouton Terminer"
analytics-category="Profil"
ng-click="disableEdditing()"
class="btn btn-lg btn-primary"
type="submit">{{ step == 2 ? 'Terminer' : 'Enregistrer' }}
</button>
</form>
</div>

Why do you send form inside edit call?
<form class="form" name="form" ng-submit="edit()">
<input type="text" ng-model="formData.name">
</form>
in your controller
$scope.edit = function() {
console.log($scope.formData)
}
Or if you want to call edit function with parameter means
<form class="form" name="form" ng-submit="edit(form)">
<input type="text" ng-model="form.name">
</form>
in your controller
$scope.edit = function(data) {
console.log(data)
}
This should work. But we don't get your problem. If you show full code, we will help.

Related

Local storage not shown after refresh

I just can't get it working no matter what I do. Been sitting for hours and nothing. After submitting form I create local storage of values name, surname, email, so that I would be able to use them to fill up form so that user would not have to type them everytime.
submit() is in review.controller.js
(function () {
'use strict';
angular.module('app').controller('ReviewController', ReviewController);
ReviewController.$inject = ['$location', 'AuthenticationService', 'FlashService', 'UniversalService', '$scope', '$sce', '$rootScope','$route','$cookies','localStorageService'];
function ReviewController($location, AuthenticationService, FlashService, UniversalService, $scope, $sce, $rootScope,$route,$cookies,localStorageService) {
var vm = this;
vm.name = null;
vm.surname = null;
vm.Email = null;
vm.review = null;
vm.allgenres = [];
vm.submit = submit;
vm.allreviews = [];
$scope.localArray=[];
loadAllReviews();
submit();
$scope.templates = [{ name: 'man.main.view.html', url: 'main/main.view.html'}];
$scope.template = $scope.templates[0];
function loadAllReviews() {
UniversalService.GetAllReviews()
.then(function (review) {
vm.allreviews = review;
});
}
$scope.init = function () {debugger;
// $scope.$MainController.obtained_array = localStorage.getItem("storageKey");debugger;
$scope.storageKey = localStorage.getItem("storageKey");debugger;
};
$scope.storageKey = localStorage.getItem('storageKey');
/* $scope.$watch("storageKey", function() {debugger;
localStorage.setItem('storageKey', storageKey);
});*/
function submit() {
if($rootScope.name!=null) {
var JSONObject = {
"name":$rootScope.name,
"surname":$rootScope.surname,
"email":$rootScope.email,
"review":$rootScope.review
}
var temp={
"name":$rootScope.name,
"surname":$rootScope.surname,
"email":$rootScope.email
}
$scope.localArray.push(temp);
localStorageService.set("storageKey", $scope.localArray);
$scope.storageKey = localStorageService.get("storageKey");
// $rootScope.obtained_array = localStorageService.get("storageKey"); debugger;
console.log($scope.storageKey);debugger;
var Results = UniversalService.PostReview(JSON.stringify(JSONObject));
}
}
}
main.controller.js
'use strict';
var app= angular.module('app').controller('MainController', MainController);
MainController.$inject = ['$location', 'AuthenticationService', 'FlashService', 'UniversalService', '$scope', '$sce', '$rootScope','$log','PagerService','localStorageService','$mdDialog'];
function MainController($location, AuthenticationService, FlashService, UniversalService, $scope, $sce, $rootScope,$log,PagerService,localStorageService,$mdDialog) {
var vm = this;
vm.allreviews = [];
vm.allusers=[];
vm.allemails=[];
vm.all=[];
vm.avatars=[];
$scope.filteredAll = [];
$scope.all=[];
$scope.items=[];
$scope.pager = {};
$scope.setPage = setPage;
loadAllReviews();
loadAllEmails();
loadAllUsers();
loadAll();
loadAvatars();
initController();
setPage();
submit();
$scope.init = function () {
$scope.$parent.storageKey = localStorage.getItem("storageKey");debugger;
// $scope.obtained_array = localStorage.getItem("storageKey");
// console.log(obtained_array); debugger;
// $scope.storageKey = localStorage.getItem("storageKey");debugger;
};
function refresh() {
location.reload();debugger;
}
function loadAll() {
UniversalService.GetAll()
.then(function (a) {
$scope.all=a;
});
}
function loadAllUsers(callback) {
UniversalService.GetAll()
.then(function (response) {
$scope.users=response;
if (callback) {
callback(response);
}
});
}
function loadAllReviews() {
UniversalService.GetAllReviews()
.then(function (review) {
vm.allreviews = review;
});
}
function loadAllEmails() {
UniversalService.GetAllEmails()
.then(function (email) {
vm.allemails = email;
});
}
function setPage(page) {
loadAllUsers(function (response) {
if (response) {
if (page < 1 || page > $scope.pager.totalPages) {
return;
}
// get pager object from service
$scope.everything=response;
$scope.pager = PagerService.GetPager(response.length, page);
// get current page of items
$scope.items = response.slice($scope.pager.startIndex, $scope.pager.endIndex + 1);
}
});
}
function initController() {
$scope.setPage(1); // initialize to page 1
}
}
HTML file:
<div class="container padding-tb" id="Review">
<div ng-controller="ReviewController" ng-init="init()" ng-app id="Review">
<h2>Add review</h2>
<form name="form" ng-submit="vm.submit()" role="form">
<div >
<div>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="text" ng-model="name" onchange="CallItems()" id="name" class="form-control" ng-model="vm.name" placeholder="Enter name here" required />
<span ng-show="form.name.$dirty && form.name.$error.required" class="help-block">Name is required</span>
</div>
</div>
<div>
<div class="form-group">
<label for="surname">Surname</label>
<input type="text" ng-model="surname" name="text" id="surname" class="form-control" ng-model="vm.surname" placeholder="Enter surname here" required/>
<span ng-show="form.surname.$dirty && form.surname.$error.required" class="help-block">Surname is required</span>
</div>
</div>
<div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" name="email" id="email" class="form-control" ng-model="vm.email" placeholder="Enter email here" required />
<span ng-show="form.email.$dirty && form.email.$error.required" class="help-block">Email is required</span>
</div>
</div>
<div>
<div class="form-group">
<label for="review">Review</label>
<input type="text" name="text" id="review" class="form-control" ng-model="vm.review" placeholder="Enter review here" required/>
<span ng-show="form.review.$dirty && form.review.$error.required" class="help-block">Review is required</span>
</div>
</div>
<div class="form-actions">
<button id="submit" type="submit" onclick="passInfo()" class="btn btn-primary">Submit</button>
<label style="display:none" id="label"><font color="white">Review succesfully created!
<a onclick="refresh()" href="../ang/#!/review">Add new review</a></label> or
View reviews!
</div>
</div>
</form>
<div>
<div ng-init="init()" class="slide-animate-container">
<div class="slide-animate" ng-include="main.view.html"></div>
</div>
</div>
</div>
Currently I add these values to button to test if values are added:
<button ng-disabled="localStorage.getItem('LS_wimmtkey') !== null"> {{obtained_array}}</button>
My main.view is inserted into the review.view (because form and reviews are on the same page, main is for the review listing and reviews are submitted form)
After submiting form all these values appear in the button, but after refreshing page none of them are shown anymore. I kind of understand that it is all because everything I do with local storage is inside submit() function, but I am not sure how to fix it
You can write a init function on second controller and set the local Storage value in a variable.So whenever you refresh the page, init function will be called and local storage value will be available for you to use it in View
see below line:
<button ng-disabled="localStorage.getItem('LS_wimmtkey') !== null"> {{obtained_array}}</button>
"obtained_array" belong to $rootScope, so $rootScope can't bind to the template(binding to $rootScope is not possible )
quick solution is: change the following line
in case of: MainController
$scope.obtained_array = localStorage.getItem("LS_wimmtkey");debugger;
in case of :ReviewController (you are setting in this ctrl "LS_wimmtkey")
$scope.$parent.obtained_array = localStorage.getItem("LS_wimmtkey");debugger;

angularjs clean input field after submission

trying to clear input filed after button is clicked and post saved with angular but it does not work. here is a simple code
<!--html-->
<input type="text" ng-model="addField"/>
<button type="button" ng-click="addPost(item)">add</button>
/*script*/
$scope.addField = '';
function addPost(item) {
/*code for adding*/
$scope.addField = "";
}
Use a object instead of string, Try this
<!--html-->
<input type="text" ng-model="form.addField"/>
<button type="button" ng-click="addPost(item)">add</button>
/*script*/
$scope.form = {};
$scope.addPost = function(item) {
/*code for adding*/
$scope.form = {};
}

How to set scope variable empty in angularjs

This is my code.
$scope.sendFeedback = function () {
var mobile1 = $scope.mobile;
var feedback1 = $scope.feedback;
var userfeedback = {
mobile: mobile1,
feedback: feedback1
};
var feedbackRef = firebase.database().ref("feedback/");
var newFeedbackRef = feedbackRef.push();
newFeedbackRef.set(userfeedback, function(error) {
if (error) {
alert ('Error while registering feedback.');
} else {
$scope.feedback = '';
alert ('Your feedback is registered.');
}
});
}
After calling this function i can see alert ('Your feedback is registered.'); but $scope.feedback = '' not setting that particulat textField as empty. I tried $scope.feedback = null; also, but no luck.
what is wrong here?
Edit: HTML View added.
<md-input-container class="md-block">
<label>Feedback</label>
<input required="" name="feedback" ng-model="feedback" >
<div ng-messages="projectForm.feedback.$error" role="alert">
<div ng-message-exp="['required']">
This field is required.
</div> </div>
</md-input-container>
I encountered that kind of problem several times, and solved it using the following workaround :
angular.element(document.getElementById('doc'))
.scope().$apply( function() {
$scope.feedback=''
)}
I made that very minimal working example, for the sake of testing the SO's snippet runner, and mostly using your own code. Hope this helps.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script>
var module=angular.module('test',[]).controller('test', function($scope)
{
$scope.click = function() {
$scope.feedback = '';
alert ('Your feedback is registered.');
}
})
</script>
</head>
<body>
<div ng-app="test" ng-controller="test" id='feedback'>
<md-input-container class="md-block">
<label>Feedback</label>
<input required="" name="feedback" ng-model="feedback" >
<div ng-messages="projectForm.feedback.$error" role="alert">
<div ng-message-exp="['required']">
This field is required.
</div> </div>
<button ng-click='click();'>click?</button>
</md-input-container>
</div>
$scope.feedback = [];
(or)
setTimeout(function () {
$scope.$apply(function () {
$scope.feedback = [];
});
}, 1000);
Do you have ng-app and ng-controller set? I tested your code on my machine, and it works as long as you have the app and controller set up.
Can you make a JSFiddle?

Meteor - preventDefault not preventing default

I'm busy with David Turnbull's - Your first Meteor Application. Everything works up to the point where I try and add a new player to the list via a form. My problem is that preventDefault is not preventing the form from trying to submit and reloading the page. return false doesn't work either.
Any ideas why this will be happening?
Thanks
PlayersList = new Mongo.Collection('players');
if (Meteor.isClient) {
//Helpers
Template.leaderboard.helpers({
'player': function() {
return PlayersList.find({}, {sort: {score: -1, name: 1}});
},
'playerCount': function() {
return PlayersList.find().count();
},
'selectedClass': function() {
var playerId = this._id;
var selectedPlayer = Session.get('selectedPlayer');
if(playerId == selectedPlayer) {
return 'selected'
}
},
'showSelectedPlayer': function() {
var selectedPlayer = Session.get('selectedPlayer');
return PlayersList.findOne(selectedPlayer);
}
});
//Events
Template.leaderboard.events({
'click .player': function() {
var playerId = this._id;
Session.set('selectedPlayer', playerId);
},
'click .increment': function() {
var selectedPlayer = Session.get('selectedPlayer');
var increaseBy = document.getElementById('increase-by').value;
var isNumber = /^\d+$/.test(increaseBy);
if(increaseBy != '' && isNumber) {
PlayersList.update(selectedPlayer, {$inc: {score: +increaseBy}});
}
},
'click .decrement': function() {
var selectedPlayer = Session.get('selectedPlayer');
var decreaseBy = document.getElementById('decrease-by').value;
PlayersList.update(selectedPlayer, {$inc: {score: -decreaseBy}});
},
'submit #new-player': function(event) {
event.preventDefault();
var playerNameVar = event.target.playerName.value;
if(playerNameVar != '') {
PlayersList.insert({
name: playerNameVar,
score:0
});
}
}
});
}
Template
<template name="addPlayerForm">
<div id="add-player" class="reveal-modal" data-reveal>
<a class="close-reveal-modal">×</a>
<h2>Add a player</h2>
<p class="lead">Add another player to the leaderboard</p>
<div class="row">
<div class="small-8 column small-centered">
<form id="new-player">
<div class="row collapse">
<div class="small-8 column">
<input type="text" placeholder="Player name" name="playerName">
</div>
<div class="small-4 column">
<input type="submit" class="button postfix" value="add player">
</div>
</div>
</form>
</div>
</div>
</div>
</template>
I've never read the book, and I don't know what your template looks like, but the problem is likely due to a selector issue.
Maybe try assigning an id to your form and mapping the submit event to that id:
// html file
<Template name="leaderboard">
<form id="new-player">
<input type="text" name="playerName">
<input type="submit" value="Submit">
</form>
</Template>
// js file
Template.leaderboard.events({
'submit #new-player': function(event) {
event.preventDefault();
...
}
});
Edit
Maybe try changing Template.leaderboard.events to Template.addPlayerForm.events.
Ok, I made the same mistake as the poster and I am putting the correct code here:
In html file:
<template name="addPlayerForm">
<form>
<input type="text" name="playerName">
<input type="submit" value="Add Player">
</form>
</template>
In js file:
Template.addPlayerForm.events({
'submit form': function(event){
event.preventDefault();
console.log("Form submitted");
console.log(event.type);
}
});

Hide a Current Button on ng-click

I have a button for updating data in ng-form. This button only appear when some form input is changed. I done this with $dirty.
When the Update is clicked, I update the data. But I want to hide this button when it clicked.
I have an ng-click method on button click.
I tried to hide it like this :-
$(this).hide();
The above solutions doesn't work & i also want some solution which is not jquery based.
HTML
<button class="btn-small" ng-click="updateData('contactinformation')" ng-show="contactinformationform.$dirty">Update</button>
CODE
$scope.updateData = function (category) {
switch (category) {
case 'basicinformation':
$scope.categorynewdata = $scope.data.basicinformation[0];
break;
case 'contactinformation':
$scope.categorynewdata = $scope.data.contactinformation[0]
break;
}
var query = {
category: category
};
Patients.updateData().save(query).$promise.then(function (data) {
alert('Data updated successfully..!');
});
}
You can use ng-hide in your button like this
Define scope variable (Like flag) so that you can decide when to hide/show button.
<button ng-click="btnClicked()" ng-hide="hideMe">Submit</button>
Controller
// Initialize hideMe variable
$scope.hideMe = false;
$scope.btnClicked = function() {
/* your code */
$scope.hideMe = true;
}
You can Try like this
Working Demo
html
<div ng-app='myApp' ng-controller="ArrayController">
<form>
<input type="text" ng-model="name" ng-change='flag=false' />: Name
<br>
<input type="text" ng-model="age" ng-change='flag=false' />: Age
<br>
<button class="btn-small" ng-click="updateData('contactinformation')" ng-hide='flag'>Update</button>
</form>
</div>
script
var app = angular.module('myApp', []);
app.controller('ArrayController', function ($scope) {
$scope.name = 'Manu';
$scope.age = '21';
$scope.flag = true;
$scope.updateData = function (value) {
$scope.flag = true;
}
});

Categories

Resources