Hello amazing Stackoverflow Coders, Please how do I empty form inputs in angular Js after form submission.
below is my working code
$rootScope.sendNow = function () {
if ($rootScope.send_login.username.length < 1)
alert("Please enter username");
else if ($rootScope.send_login.password.length < 1)
alert("Please enter password");
else {
$http.post($rootScope.server_url + "post_Data", $rootScope.send_login)
.success(function (response)
{
// on success
$('#send_login.username').val('');
$('#send_login.password').val('');
toastr.success('Successful');
}
).error(function (response)
{
alert("sending failed");
});
}
};
My Form is here below
<input type="text" id="username" name="username" ng-value="send_login.username">
<input type="text" id="pass" name="pass" ng-value="send_login.password">
<input type="button" ng-click="sendNow()" value="Send">
Unlike Ajax, I have tried this below but cannot get it to work
$('#send_login.username').val('');
$('#send_login.password').val('');
you should use ng-model in the input tag, like:
html:
<input type="text" ng-model="name">
<button ng-click="sendData()"> Send</button>
js (angularjs Controller):
$scope.sendData = function (item) {
$scope.name = "";
}
Its better to take every form field ng-modal as a property of a object, like you have taken in "send_login".
After form submission reinitialize this object send_login = {};
Every field will be reinitialize. and a undefined property doesn't create a error in angular.
You should avoid so much use of $rootScope in your code.
You need to change ng-value to ng-model (to bind the angular variable to html input) and on ajax success clear the binded variable:
$http.post('...').success(function (response) {
$rootScope.send_login = {};
});
Related
I have this html:
<div ng-controller="My.MarkdownEditorController">
<a target="_default" ng-click="changeValue()" class="btn btn-info">Copy Organisation Address to Member</a>
</div>
The Angular controller for the click is:
angular.module("umbraco").controller("My.MarkdownEditorController",
function ($scope, $http) {
$scope.changeValue = function () {
//changes value but it doesn't save
//what is the Angular way to do this correctly
document.getElementById('title').value= document.getElementById('title').value + '2';
};
});
How do I change the value of the adjacent text box with id "title" correctly?
The above code modifies the value, but it doesn't save.
I think that's because I am not changing it the Angular way.
The html of the input I am trying to modify is:
<input type="text" id="title" name="textbox" ng-model="model.value" class="umb-property-editor umb-textstring textstring ng-pristine ng-untouched ng-valid ng-isolate-scope ng-valid-val-server ng-not-empty ng-valid-required" val-server="value" ng-required="model.validation.mandatory" aria-required="false" aria-invalid="False" ng-trim="false" ng-keyup="change()">
I got this working but not sure if it is correct:
angular.module("umbraco").controller("My.MarkdownEditorController",
function ($scope, $http) {
$scope.changeValue = function () {
var title = $("#title");
title.val("this is how to do it");
setTimeout(function(){ title.trigger("input") }, 10);
};
});
Your input: <alue" ng-keyup="change()">
You have javascript value model.value and html input value. These two are connected via ng-model:
After you change scope value $scope.model.value = ... angularjs will update html input value.
After user changes html input value, angularjs will update your scope value.
You should nealy never change html input value directly, you should change scope value (it wont trigger ng-keyup or ng-change).
P.S. avoid using ng-keyup in inputs - there is copy-paste and drag-drop that may change input as well.
I have a simple form like so:
<form name="add-form" data-ng-submit="addToDo()">
<label for="todo-name">Add a new item:</label>
<input type="text" data-ng-model="toDoName" id="todo-name" name="todo-name" required>
<button type="submit">Add</button>
</form>
with my controller as follows:
$scope.addToDo = function() {
if ($scope.toDoName !== "") {
$scope.toDos.push(createToDo($scope.toDoName));
}
}
what I'd like to do is clear the text input after submission so I simply clear the model value:
$scope.addToDo = function() {
if ($scope.toDoName !== "") {
$scope.toDos.push(createToDo($scope.toDoName));
$scope.toDoName = "";
}
}
Except now, because the form input is 'required' I get a red border around the form input. This is the correct behaviour, but not what I want in this scenario... so instead I'd like to clear the input and then blur the input element. Which leads me to:
$scope.addToDo = function() {
if ($scope.toDoName !== "") {
$scope.toDos.push(createToDo($scope.toDoName));
$scope.toDoName = "";
$window.document.getElementById('todo-name').blur();
}
}
Now, I know that modifying the DOM from the controller like this is frowned upon in the Angular documentation - but is there a more Angular way of doing this?
When you give a name to your form it automatically gets added to the $scope.
So if you change your form name to "addForm" ('cause I don't think add-from is a valid name for angular, not sure why), you'll have a reference to $scope.addForm.
If you use angular 1.1.1 or above, you'll have a $setPristine() method on the $scope.addForm. which should recursively take care of resetting your form. or if you don't want to use the 1.1.x versions, you can look at the source and emulate it.
For those not switching over to 1.1.1 yet, here is a directive that will blur when a $scope property changes:
app.directive('blur', function () {
return function (scope, element, attrs) {
scope.$watch(attrs.blur, function () {
element[0].blur();
});
};
});
The controller must now change a property whenever a submit occurs. But at least we're not doing DOM manipulation in a controller, and we don't have to look up the element by ID:
function MainCtrl($scope) {
$scope.toDos = [];
$scope.submitToggle = true;
$scope.addToDo = function () {
if ($scope.toDoName !== "") {
$scope.toDos.push($scope.toDoName);
$scope.toDoName = "";
$scope.submitToggle = !$scope.submitToggle;
}
};
}
HTML:
<input type="text" data-ng-model="toDoName" name="todo-name" required
blur="submitToggle">
Plnkr
I have made it work it as below code.
HTML SECTION
<td ng-show="a">
<input type="text" ng-model="e.FirstName" />
</td>
Controller SECTION
e.FirstName= '';
I have a text input in a form that I want to fill with data I'm getting from a promise.
this is my text input :
<input type="text" name="lastname" id="lastname" class="form-control input-lg"
ng-model="candidature.lastname"
required>
And In my controller I have this :
candidatureService.get({id: $rootScope.username}).$promise.then(function (res) {
$scope.candidature = {};
$scope.candidature.lastname = res.nom;
//code...
}).catch(function (err) {
console.log('Error getting data');
});
When I inspected my application using batrang I can see that the object candidature in $scope has the value I'm getting using that promise :
And as you can see I have ng-model="candidature.lastname".
Does anyone know why the text input doesn't get the value from the scope?
Thanks in advance.
Try declaring $scope.candidature = {}; before you make the API request...
But from the code it looks like you have only declared $scope.candidature.lastname and not $scope.candidature.firstname.
I have form in which there are couple of text fields and an email field.
I want to validate all fields for required / mandatory validation. I want to validate email field for email format validation. I want to carry out validation only when I click on two buttons and show the validation messages at top of the page. I know that I can check for email and required validations on field and using ng-show and a flag I can show messages. However I want to check each field's value in a directive and then set the flag to true which will make the message appear.
Here is my HTML. this gets loaded why state provider in main page which also defines following template and a controller for it. so its just a view partial:
<form name="myForm">
<div ng-show="validationFailed">
<!-- here i want to display validation messages using cca.validationMsgs object -->
</div>
<input type="text" name="test" ng-model="cca.field1" require />
....
<input type="email" mg-model="cca.field2" />
<input type="button" name="mybutton" />
</form>
Now the controller defined in another JS file:
'use strict';
(function(){
angular.module('store', []);
app.controller("StoreController",function(){
var cca = this;
cca.validationMsgs = {};
cca.validationFailed = false; //this flag should decide whether validation messages should be displayed on html page or not.when its true they are shown.
...//other mapped fields
});
And here is unfinished directive which I want to define and write my logic. Logic will be something like this :
1) iterate all elements which have require set on them and check their
$validators object / $error.required object is set
2) if yes set validationFailed flag to true,add the validation message to validationMsgs object and break the loop.
3) check if email type field has $error.email object set and if yes
similarly set validationFailed flag to true and add corresponding message to the object. Not sure if I really need a directive for this. I would like to apply the directive inside a element.
app.directive("requireOnSubmit",function(){
var directiveDefinitionObject = {
restrict:'E',
//.... need to fill in
//I can use link funcion but not sure how to map
// validationMsgs and validationFailed objects in here.
};
return directiveDefinitionObject;
});
Without any code or use case to go after I'll just show you a generic way of validating input. I'm going to use a signup functionality as an example.
Create a service/factory which will carry out the validation and return a promise, if the validation fails it will reject the promise. If not, it will resolve it.
Important note: A promise can only be resolved once (to either be fulfilled or rejected), meaning that the first declaration of a resolve or reject will always "win", which means you can't override any resolve or reject. So in this example if a field is empty and a user's email is undefined, the error message will be All fields must be filled in and not Invalid email format.
auth.factory('validation', ['$q', function($q) {
return {
validateSignup: function(newUser) {
var q = $q.defer();
for (var info in newUser) {
if (newUser[info] === '') {
q.reject('All fields must be filled in');
}
}
if (newUser.email === undefined) {
q.reject('Invalid email format');
}
else if (newUser.password.length < 8) {
q.reject('The password is too short');
}
else if (newUser.password != newUser.confirmedPass) {
q.reject('The passwords do not match');
}
q.resolve(true);
return q.promise;
}
}
}]);
And then inject this into your controller
auth.controller('AuthCtrl', ['$scope', '$location', 'validation', function($scope, $location, validation) {
$scope.status = {
message: ''
}
// Make sure nothing is undefined or validation will throw error
$scope.newUser = {
email: '',
password: '',
confirmedPass: ''
}
$scope.register = function() {
// Validation message will be set to status.message
// This will also clear the message for each request
$scope.status = {
message: ''
}
validation.validateSignup($scope.newUser)
.catch(function(err) {
// The validation didn't go through,
// display the error to the user
$scope.status.message = err;
})
.then(function(status) {
// If validation goes through
if (status === true) {
// Do something
}
});
}
And in the HTML you can have something like this:
<form>
<div>
<label for="email">Email:</label>
<input type="email" id="email" ng-model="newUser.email">
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="confirm-pass" ng-model="newUser.password">
</div>
<div>
<label for="confirm-pass">Confirm password:</label>
<input type="password" id="confirm-pass" ng-model="newUser.confirmedPass">
</div>
<div>
<div>
<span ng-bind="status.message"></span>
</div>
</div>
<div>
<button ng-click="register(newUser)">Register</button>
</div>
</form>
You can use this example and modify it for your use case.
I have a simple form like so:
<form name="add-form" data-ng-submit="addToDo()">
<label for="todo-name">Add a new item:</label>
<input type="text" data-ng-model="toDoName" id="todo-name" name="todo-name" required>
<button type="submit">Add</button>
</form>
with my controller as follows:
$scope.addToDo = function() {
if ($scope.toDoName !== "") {
$scope.toDos.push(createToDo($scope.toDoName));
}
}
what I'd like to do is clear the text input after submission so I simply clear the model value:
$scope.addToDo = function() {
if ($scope.toDoName !== "") {
$scope.toDos.push(createToDo($scope.toDoName));
$scope.toDoName = "";
}
}
Except now, because the form input is 'required' I get a red border around the form input. This is the correct behaviour, but not what I want in this scenario... so instead I'd like to clear the input and then blur the input element. Which leads me to:
$scope.addToDo = function() {
if ($scope.toDoName !== "") {
$scope.toDos.push(createToDo($scope.toDoName));
$scope.toDoName = "";
$window.document.getElementById('todo-name').blur();
}
}
Now, I know that modifying the DOM from the controller like this is frowned upon in the Angular documentation - but is there a more Angular way of doing this?
When you give a name to your form it automatically gets added to the $scope.
So if you change your form name to "addForm" ('cause I don't think add-from is a valid name for angular, not sure why), you'll have a reference to $scope.addForm.
If you use angular 1.1.1 or above, you'll have a $setPristine() method on the $scope.addForm. which should recursively take care of resetting your form. or if you don't want to use the 1.1.x versions, you can look at the source and emulate it.
For those not switching over to 1.1.1 yet, here is a directive that will blur when a $scope property changes:
app.directive('blur', function () {
return function (scope, element, attrs) {
scope.$watch(attrs.blur, function () {
element[0].blur();
});
};
});
The controller must now change a property whenever a submit occurs. But at least we're not doing DOM manipulation in a controller, and we don't have to look up the element by ID:
function MainCtrl($scope) {
$scope.toDos = [];
$scope.submitToggle = true;
$scope.addToDo = function () {
if ($scope.toDoName !== "") {
$scope.toDos.push($scope.toDoName);
$scope.toDoName = "";
$scope.submitToggle = !$scope.submitToggle;
}
};
}
HTML:
<input type="text" data-ng-model="toDoName" name="todo-name" required
blur="submitToggle">
Plnkr
I have made it work it as below code.
HTML SECTION
<td ng-show="a">
<input type="text" ng-model="e.FirstName" />
</td>
Controller SECTION
e.FirstName= '';