Input field should not clear after submit using angularjs - javascript

HTML
<form ng-controller="updatecontroller" ng-submit="updateUser()"><label class="control-label">First Name</label>
<input type="text" ng-model="user.userFirstName">
<label class="control-label">Last Name</label>
<input type="text" ng-model="user.userLastName" ><button type="submit" ng-click="updateUser()">Update</button>
</form>
JS
app.controller('updatecontroller', function ($scope, $http, $cookieStore) {
$http.get('http://localhost:8080/myapp/user/'.concat($scope.getUserId) + '?access_token=' + $cookieStore.get("access_token")).
then(function (response) {
$scope.user = response.data;
});$scope.user = {"id": "","userFirstName": "","userLastName": ""}
$scope.updateUser = function () {
var url = "http://localhost:8080/myapp/user/".concat($scope.getUserId) + "?access_token=" + $cookieStore.get("access_token");
var method = "PUT";
$http({
method: method,
url: url,
data: angular.toJson($scope.user),
headers: {
'Content-Type': 'application/json'
}
})
};});
values will appear in text field. i have to update. the values are getting updated in database. but what i want is.. the updated values should not clear after submit the form.
Thanks!

You can empty the input filed after get the response from HTTP request
$scope.updateUser = function () {
$http({
method: 'POST',
url: 'myUri',
data: 'your data'
headers:'header'
}).then(
function(res) {
$scope.user = {"id": "","userFirstName": "","userLastName": ""} //clear the input field here
},
function(err) {
}
);
}

Place your Submit Button inside the Form Element then try it it will clear the input after the submission.

your updateUser() method seems to be the problem. It's probably clearing user.userFirstName & user.userLastName (or the whole user)
please show us what updateUser() is doing to be sure

Related

Converting to string NodeJS Express http response returns in AngularJS

I am trying to build an angularjs program which talks to express / nodejs api and mysql database.
In login page , I am able to call the api correctly and it connects with mysql and based on right combination of user name and password , I am sending back "password matches" or "failure".
When I am accessing that on HTML using $scope , I am getting ["password matches"] and not password matches . I have tried toString, splice, etc but no proper result.
Controller
var passStats=[];
passStats = LoginFactory.validateUserLoginFactory(uName, pWD)
$scope.pwdStatus = passStats;
Factory
app.factory("LoginFactory", function ($http) {
var factory = {};
factory.validateUserLoginFactory = function (UserName, PWD) {
$http({ method: "POST", url: 'http://localhost:3000/validateUserLogin/', data: { limit: userForm }, cache: false }).then(function (response) {
StatusPWD.push(response.data);
}, function (error) { console.log(error); });
return StatusPWD;
}
return factory;
});
node.js
res.send('password matches');
HTML
<label>User Name</label>
<input type="text" ng-model="enteredUserName" class="w3-input w3-border w3-padding">
<br>
<label>Password</label>
<input type="text" ng-model="enteredPWD" class="w3-input w3-border w3-padding">
<br>
<input type="button" ng-Click="validateLogin(enteredUserName,enteredPWD)" value="Login" class="w3-btn w3-padding w3-green">
<br> <br> <br>
<label>password {{ pwdStatus}}</label>
It is because you are using StatusPWD.push which is pushing it into an array.
the passStats variable is an array, where you are pushing the response.
you can simply do this to get the value if passStats is an array
$scope.pwdStatus = passStats[0]
or you can do
$scope.pwdStatus = passStats.join("")
I have solved my problem for which I posted the question. I had coded the factory and controller part wrongly. Following modification is giving me proper out put in HTML
Factory
factory.validateUserLoginFactory = function (UserName, PWD) {
var userForm = {};
userForm = { user: UserName, password: PWD };
return $http({ method: "POST", url: 'http://localhost:3000/validateUserLogin/', data: { limit: userForm }, cache: false });
}
Controller
$scope.pwdStatus;
LoginFactory.validateUserLoginFactory(uName, pWD)
.then(function (data) {
console.log(data.data);
$scope.pwdStatus = data.data;
}, function (data) {
console.log(data);
});

Refresh/ Re Render the UI once Submit button is clicked

Currently I am using AnularJS to update the value from JSON file and Once I click Submit button , I want to clear the whole DOM and refresh the UI and update the contents. Can you please help here
Here Value1 and Value2 comes from two different functions but sometimes . Value2 will be null and only Value1 will be present. but still Value2 will be shown with Old value and Value1 with updated value after clicking submit button.
Is there any way in AngularJS to refresh the DOM before updating the values. so that once i click submit i should be seeing only Value1
var app = angular.module('myApp', ['angular-loading-bar']);
app.controller("Controller", ["$scope", "$http", "$window",
function ($scope, $http, $window) {
$scope.firstFunction = function () {
$http({
method: 'POST',
url: 'one.php',
//headers : {'Content-Type':'application/x-www-form-urlencoded'},
data: {
"accountnumber": $scope.accountnumber,
"environment": $scope.selectedVal,
},
}).then(function (response) {
var data = response.data;
$scope.post = response.data;
$scope.value1 = response.data
//$scope.secondFunction(data);
}, function (error) {
var data = error.data;
console.log("Error" + data);
})
}
$scope.secondFunction = function () {
$http({
method: 'POST',
url: 'two.php',
//headers : {'Content-Type':'application/x-www-form-urlencoded'},
data: {
"accountnumber": $scope.accountnumber,
"environment": $scope.selectedVal,
},
}).then(function (response) {
var data = response.data;
$scope.post = response.data;
$scope.value2 = response.data
console.log($scope.cellularIPAddressValue);
//$scope.secondFunction(data);
}, function (error) {
var data = error.data;
console.log("Error" + data);
})
}
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html>
<body ng-app="myApp">
<div ng-controller="Controller">
<div class="row">
<div class="input-group form-search">
<input type="text" ng-model="accountnumber" name="accountnumber" class="form-control search-query" placeholder="Enter Account Number">
<span class="input-group-btn">
<button type="submit" ng-click="firstFunction();secondFunction();" class="btn btn-primary">Submit</button>
</span>
<span id="message">{{value1}}</span>
<span id="message">{{value2}}</span>
</div>
</div>
</div>
</body>
</html>
There is no need to refresh UI as angular data-binding does the job.
Changing the ng-click="firstFunction();secondFunction();"
to ng-click="value1=null;value2=null;firstFunction();secondFunction();" may help.

angularjs http post method

Trying to post something back to the mongodb however its not sending anything, when I click submit its passing {} back to the cmd and the network console is hanging on pending then it will fail when its taking long to post.
Can someone shed a light on this one please, thanks.
Html:
<input type="text" ng-model="vm.user">
<input type="text" ng-model="vm.pass">
Service:
function _postUser(user,pass){
var params = {
user: user,
pass:pass
}
return $http({
method: 'POST',
url: '/loginDB',
params: params
})
}
Get users: I get the users from the DB.
vm.getUsers = function (){
homeService.getUsers()
.then(function(response){
vm.users = response.data;
console.log(vm.users);
});
}
Post action:
vm.postUser = function() {
// console.log('send it back')
homeService.postUser(vm.user)
.then(function(response){
console.log('send it back')
})
}
Server.js app.post back to db
app.post('/loginDB', function (req, res){
console.log(req.body);
});
Edit: its posting but now taking the ng-model, I know something is wrong with the ng-model but just can't get my head on it.
db.loginDB.insert(req.body, function(err, doc){
res.json(doc);
})
Try changing params key to data
return $http({
method: 'POST',
url: '/loginDB',
data: params
})
In the html too you have the same model for both the inputs,
controller declaration,
vm.newuser = {user:'',pass:''};
html
<input type="text" ng-model="vm.newuser.user">
<input type="text" ng-model="vm.newuser.pass">

How to submit a straightforward form using Angular

Using angular, I want to submit a form and store the response. My code looks something like this:
<form ng-controller="myController" action="myAction" method="POST">
<input type="text" name="name" />
<input type="submit" ng-click="submit" />
</form>
<script>
function myController($scope, $http) {
$scope.submit = function() {
$http.post(url, data).success(function(data) {
$scope.result = data;
});
}
}
</script>
How do I get url and data to be the form action and inputs, respectively? I don't want to send JSON, I want the server side to see this is a regular HTML form submit.
Thank, #Vincent Ramdhanie, for pointing me in the right direction. Here's what I ultimately did, using plenty of jQuery thrown in:
function myController($scope, $http) {
$('form').submit(function() {
return false;
});
$scope.submit = function() {
form = $('form');
data = form.serialize();
url = form.attr('action')
$http.post(url, data,
{ headers:
{ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function(data) {
$scope.result = data;
}
);
}
}
This is how I accomplish this, start by binding the form data to your model, Then use a transform to transform your JSON data into regular post parameters. This solution depends on the jQuery param() function:
<form ng-controller="myController" method="POST">
<input type="text" name="name" ng-model="name"/>
<input type="submit" ng-click="submit" />
</form>
function myController($scope, $http) {
$scope.name = "";
/* Helper function to transform the form post to a regular post rather than JSON */
var transform = function(data) {
return $.param(data);
}
$scope.submit = function() {
$http.post('myAction', $scope.name, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
transformRequest: transform
})
.success(function (data) {
$scope.result = data;
});
}
}

Angular.js accessing model from controller (server validation)

i now trying to migrate my legace app to Angular and now stuck with following issue.
I have this simple form:
<form name="loginForm" ng-controller="LoginCtrl" ng-submit="doLogin()">
<input type="text" name="login" ng-model="login.login" />
<span class="errors" ng-show="loginForm.login.$error.required">Required</span>
<span class="errors" ng-show="loginForm.login.$error.bad_login">Login or pass incorrect</span>
<input type="password" ng-model="login.pass"/>
</form>
Server returns error as this type of JSON: { login: 'bad_login', pass: 'incorrect' }
And in controller:
function LoginCtrl($scope, $http) {
$scope.doLogin = function() {
var model = $scope.login;
var req = { "login": model.login, "pass": model.pass };
$http({ method: "POST", url: "/login", data: req }).success(function (resp) {
if(resp.status != "ok") {
angular.forEach(resp, function (value, key) {
// ex: model['login'].$setValidity('bad_login', false);
model[key].$setValidity(value, false);
});
}
});
};
}
I try to mark each field in loop, not to hardcode every field by hand. but this approach not working. I get this error: TypeError: Cannot call method '$setValidity' of undefined, even when field is left empty i have another error: TypeError: Cannot read property 'login' of undefined
So i think i need to get instance of model for every field in form, any ideas ?
The reason it's coming back undefined is because unless you actually specify something for $scope.login.login or $scope.login.pass to begin with, they aren't set. If you put a space and delete it, you'll see they are set as blank. What you're going to want to do is at the beginning of your controller define the login on the scope like so:
function LoginCtrl($scope, $http) {
$scope.login = {
login: "",
pass: ""
};
$scope.doLogin = function() {
var req = { "login": $scope.login.login, "pass": $scope.login.pass };
$http({ method: "POST", url: "/login", data: req }).success(function (resp) {
if(resp.status != "ok") {
angular.forEach(resp, function (value, key) {
// ex: model['login'].$setValidity('bad_login', false);
$scope.login[key].$setValidity(value, false);
});
}
});
};
}

Categories