I am new to angular. I have looked up a lot of answers on clearing form fields after submitting but none seems to work.
Here's my HTML code:
<form name="myForm" ng-submit="formSubmit()" class="form-horizontal">
<div class="form-group">
<input type="text" class="form-control" ng-model="user.FullName" placeholder="Full Name" required=""/>
</div>
<div class="form-group">
<input type="text" class="form-control" ng-model="user.Address" placeholder="Address" required=""/>
</div>
<button type="submit" class="btn btn-primary" style="background-color: purple;">Submit</button>
</form>
Here's my JS code:
var myApp = angular.module('myApp', ['ui.router']);
myApp.controller("RegisterCtrl", function ($window,$scope,$http) {
$scope.user={}
$scope.formSubmit=function(){
$http({
method:'POST',
url:'myurl',
data:$scope.user,
headers:{'Content-Type':'application/json'}
}).then(function(res){
console.log(res);
$scope.myForm.$setPristine();
$scope.myForm.$setPristine(true);
$scope.myForm='';
})
}
});
I have tried setPristine as well as setUntouched but none working.
I don't see something strange in your code, i make plnkr based on your code, the modifications i do are below. also put the plnkr sample
CONTROLLER
var myApp = angular.module('myApp', ['ui.router']);
myApp.controller("RegisterCtrl", function ($window,$scope,$http) {
$scope.user={}
$scope.formSubmit=function(){
$http({
method:'POST',
url:'myurl',
data:$scope.user,
headers:{'Content-Type':'application/json'}
}).then(function(res){
$scope.myForm.$setPristine();
$scope.user = {};
}, function(rej){ //error});
}
});
you should try
var myApp = angular.module('myApp', ['ui.router']);
myApp.controller("RegisterCtrl", function ($window,$scope,$http) {
$scope.user={}
$scope.formSubmit=function(){
$http({
method:'POST',
url:'myurl',
data:$scope.user,
headers:{'Content-Type':'application/json'}
}).then(function(res){
$scope.$broadcast('show-errors-reset');
$scope.forms.user = {};
$scope.forms.userFrom.$setPristine = true;
}, function(rej){ //error});
}
});
Related
I´m currently working on a login-page for a school-prohect. I´m using vue.js and tried to use axios to run my get-request. My problem is, that I don´t even get into .then() --> alert(TEST1) is the last thing showed.
I don´t get any error
Does anyone know why I have this problem and how to solve it?
Thanks!
CODE:
<template>
....
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6" id="formsCSS">
<form id="login" method="get">
<div class="form-group">
<input type="text" name="username" id="username" class="form-control" placeholder="Username" required maxlength="50">
</div>
<div class="form-group">
<input type="password" name="password" class="form-control" id="password" placeholder="Password" required>
</div>
<button #click="login" type="submit" name="login_button" class="block">Login</button>
</form>
....
</div>
</template>
<script>
//import axios from './node_modules/axios/index.js';
import axios from 'axios';
export default {
methods: {
login() {
var usrn = document.getElementById("username").value;
var passwd = document.getElementById("password").value;
var usesGranted = 50;
alert("TEST0");
this.doGetRequest(usrn, passwd, usesGranted, false);
},
doGetRequest(passwd, usrn, usesGranted, logedIn) {
alert("TEST1");
axios.get('https://moray.xyz/trawaapi/token/obtainToken.php', {
data: {
auth: {
username: usrn,
password: passwd
},
uses: usesGranted
}
})
.then((response) => {
//Informationen die für Requests benötigt werden in der sessionStorage abspeichern
alert("TEST2");
console.log(response);
sessionStorage.setItem("token", response);
sessionStorage.setItem("password", passwd);
sessionStorage.setItem("username", usrn);
sessionStorage.setItem("uses", usesGranted)
})
.catch((error) => {
//Neuen Token anfordern
if (error == 401) {
if (logedIn == true)
alert("....");
}
console.error(error);
});
}
}
};
</script>
You have to prevent form from being sent. Change remove onclick from button and add another event to the form tag:
<form #submit.prevent="yourFunction" id="login">
As we prevent Email sending and just running yourFunction - we do not need to use method attribute.
I am writing a login page with register and login options using AngularJS. There are three input fields: username, password and name. I want name field to appear when I click to register button and disappear when I click to login button. Therefore I want to change input field's class to 'hidden' on click and let css handle the job. How can I do it using AngularJS? Is there a better way to hide the name input field?
HTML:
<h2>Welcome to Mail Service</h2>
<form action="/action_page.php">
<div class="imgcontainer">
<img src="images/img_avatar2.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label><br>
<input type="text" placeholder="Enter Username" name="uname" required ng-model="user.username"><br>
<label><b>Password</b></label><br>
<input type="password" placeholder="Enter Password" name="psw" required ng-model="user.password"><br>
<!-- NAME INPUT FIELD -->
<div class="textField-hidden">
<label><b>Name</b></label><br>
<input type="text" placeholder="Enter Name" ng-model="user.name">
</div><br>
<button type="submit" ng-click="login()">Login</button><br>
<button type="submit" ng-click="register()">Register</button>
</div>
</form>
AngularJS Controller:
app.controller('LoginCtrl', ['$scope', '$resource', '$location',
function($scope, $resource, $location)
{
$scope.login = function()
{
var loginRequest = $resource('/api/login');
loginRequest.save($scope.user, function(response)
{
});
};
$scope.register = function()
{
var registerRequest = $resource('/api/register');
loginRequest.save($scope.user, function(response)
{
});
};
}]);
You need to use ng-hide or ng-show directive (based on your context), and provide it with appropriate condition value like this:
$scope.showName = false;
$scope.login = function() {
// Your code
$scope.showName = false;
}
$scope.register = function() {
// Your code
$scope.showName = false;
}
Change your HTML accordingly:
<input ng-show="showName" type="{{type}}" placeholder="Enter Name" ng-model="user.name">
In this way, the input box will be shown only if the expression of ng-show evaluates to true. Alternatively, ng-if can be used similar to ng-show, but it works a bit different.
just populate a variable as true when you click register and set that variable as false when you click login.
<h2>Welcome to Mail Service</h2>
<form action="/action_page.php">
<div class="imgcontainer">
<img src="images/img_avatar2.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label><br>
<input type="text" placeholder="Enter Username" name="uname" required ng-model="user.username"><br>
<label><b>Password</b></label><br>
<input type="password" placeholder="Enter Password" name="psw" required ng-model="user.password"><br>
<!-- NAME INPUT FIELD -->
<div class="textField-hidden" ng-show="register">
<label><b>Name</b></label><br>
<input type="text" placeholder="Enter Name" ng-model="user.name">
</div><br>
<button type="submit" ng-click="login()">Login</button><br>
<button type="submit" ng-click="register()">Register</button>
now populate $scope.register as true when you click register
app.controller('LoginCtrl', ['$scope', '$resource', '$location',
function($scope, $resource, $location)
{
$scope.register=false;
$scope.login = function()
{
var loginRequest = $resource('/api/login');
$scope.register=false;
loginRequest.save($scope.user, function(response)
{
});
};
$scope.register = function()
{
var registerRequest = $resource('/api/register');
$scope.register=true;
loginRequest.save($scope.user, function(response)
{
});
};
}]);
You can use a variable for input fields type and hide it
HTML:
<input type="{{type}}" placeholder="Enter Name" ng-model="user.name">
JS:
app.controller('LoginCtrl', ['$scope', '$resource', '$location',
function($scope, $resource, $location)
{
$scope.login = function()
{
$scope.type="hidden";
var loginRequest = $resource('/api/login');
loginRequest.save($scope.user, function(response)
{
});
};
$scope.register = function()
{
$scope.type="text";
var registerRequest = $resource('/api/register');
loginRequest.save($scope.user, function(response)
{
});
};
}]);
An alternative will be to use ng-if or ng-hide/ng-show defined on a $scope variable and trigger a boolean value for this variable according to your needs.
I have a application running with a flask backend and angular frontend. Apparently when a wrong password is entered i want to show a error message. I have tried out ng-show and ng-if both nothing seems to work.
This is the html for my login page -
<div layout="column" layout-align="center center" class="">
<img class="logo" ng-src="assets/images/logo.png">
<h1 class="md-display-2 login-heading">Login to Bassa</h1>
<div layout="row">
<md-input-container>
<label>User name</label>
<input type="text" ng-model="user.user_name"/>
</md-input-container>
<md-input-container>
<label>Password</label>
<input type="password" ng-model="user.password" ng-enter="login()"/>
</md-input-container>
<br>
</div>
<div>
<md-button class="md-raised md-primary" ng-click="login()">Login</md-button>
<md-button class="md-raised md-primary" ng-click="signup()">Signup</md-button>
</div>
And this is the login controller -
(function(){
'use strict';
angular
.module('app')
.controller('LoginCtrl', ['$scope', '$state', 'UserService', LoginCtrl]);
function LoginCtrl($scope, $state, UserService) {
$scope.user = {};
$scope.incorrectCredentials = false;
$scope.login = function(){
UserService.login($scope.user, function(status) {
if (status){
$state.go('home.dashboard');
} else {
$scope.incorrectCredentials = true;
}
});
};
$scope.signup = function() {
$state.go('signup');
};
UserService.removeToken();
}
})();
When the incorrectCredentials becomes true , i want to show a message.
After logging the User service -
var login = function(credentials, cb) {
var $http = $injector.get('$http');
return $http({
method: 'POST',
url: BassaUrl + '/api/login',
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
return str.join('&');
},
data: credentials,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
setToken(response.headers()['token']);
setName(credentials.user_name);
setAuthLevel(response.data.auth);
console.log(response);
cb(true);
}, function(error){
console.log("hello i am here")
cb(false);
});
};
I received a response log -
Object {data: "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final/…ead-protected or not readable by the server.</p>↵", status: 403, config: Object, statusText: "FORBIDDEN"}
It isn't entering the error block , which prevents me from prompting wrong password message.
It was actually my own fault. My custom Interceptor simply swallowed authentication errors.
I am trying to send the values from html to controller but is not goes to controller. What is the problem with this code value is show undefined at controller and factory. I hope this code is easy understood:
var mymodal = angular.module('mymodal', []);
mymodal.controller('MainCtrl', function($scope, loginfactory) {
$scope.showModal = false;
$scope.toggleModal = function() {
$scope.showModal = !$scope.showModal;
};
$scope.doLogin = function() {
var promise = loginfactory.logincheck($scope.userid, $scope.pwd);
}
});
mymodal.factory("loginfactory", function($http, $q) {
return {
"logincheck": function(userid, pwd) {
console.log(userid);
console.log(pwd);
return Object;
}
};
});
mymodal.directive('modal', function() {
return {
template: '<div class="modal fade">' +
'<div class="modal-dialog">' +
'<div class="modal-content">' +
'<div class="modal-header">' +
'<button type="button" class="close" data-dismiss="modal" aria-hidden="">×</button>' +
'<h4 class="modal-title">{{ title }}</h4>' +
'</div>' +
'<div class="modal-body" ng-transclude=""></div>' +
'</div>' +
'</div>' +
'</div>',
restrict: 'E',
transclude: true,
replace: true,
scope: true,
link: function postLink(scope, element, attrs) {
scope.title = attrs.title;
scope.$watch(attrs.visible, function(value) {
if (value == true)
$(element).modal('show');
else
$(element).modal('hide');
});
$(element).on('shown.bs.modal', function() {
scope.$apply(function() {
scope.$parent[attrs.visible] = true;
});
});
$(element).on('hidden.bs.modal', function() {
scope.$apply(function() {
scope.$parent[attrs.visible] = false;
});
});
}
};
});
My view:
<div ng-controller="MainCtrl" class="container">
<h1>Modal example</h1>
<button ng-click="toggleModal()" class="btn btn-default">Open modal</button>
<modal title="Login form" visible="showModal">
<form role="form">
<div class="form-group">
<label for="email">Email address</label>
<input type="text" class="form-control" ng-model="userid" placeholder="Enter email" />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" ng-model="pwd" placeholder="Password" />
</div>
<button type="submit" ng-click="doLogin()" class="btn btn-default">Submit</button>
</form>
</modal>
</div>
Here is what I mean see Plunker;
In your directive you used: scope: true, this mean what is change in the directive will not reflect on the parent scope Look at this so to get it works you have to do like this. in the submit btton: (angular best practice passing scope from view)
<button ng-click="doLogin(userid,pwd)" class="btn btn-default">submit</button>
in your controler:
$scope.doLogin = function(userid,pwd) {
var promise = loginfactory.logincheck(userid, pwd);
}
you see I don't pass $scope.userid and $scope.pwd in your loginfactory but pass the value from view because of scope: true, make your code won't work.
one last suggest, you can use UI bootstrap for angular so you don't have to mix with jquery bootstrap. UI Bootstrap
I have a angular-ui modal, that is controlled with below controller:
var emailModal = angular.module('myApp.emailModal', ['ui.bootstrap', 'ui.bootstrap.tpls']);
emailModal.controller('ModalCtrl', ['$scope', '$uibModal', function ($scope, $uibModal) {
$scope.open = function () {
var modalInstance = $uibModal.open({
templateUrl: 'components/emailModal/emailModalView.html',
backdrop: true,
controller: 'modalInstanceCtrl'
});
}
}]);
emailModal.controller('modalInstanceCtrl', function ($scope, $uibModalInstance, $http) {
//create blank object to handle form data.
$scope.user = {};
//calling our submit function.
$scope.submitForm = function() {
//posting data to php file
$http({
method: 'POST',
url: 'components/emailModal/emailInsert.php',
data: $scope.user, //forms user object
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
if (data.errors) {
//showing errors.
$scope.errorEmail = data.errors.email;
} else {
$scope.message = data.message;
}
});
};
});
This is the actual modal view:
<form name="userForm" ng-submit="submitForm()">
<div class="modal-header">
<h3 class="modal-title">Register</h3>
</div>
<div class="modal-body">
<div class="form-group">
<label>E-Mail Address</label>
<input type="email" name="email" class="form-control" ng-model="user.email" placeholder="Email address" />
<span ng-show="errorEmail">{{errorEmail}}</span>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
Modal loads with no problem, bute once clicked to submit, nothing happens. I get no error once so ever in the console. What am I doing wrong? This is my PHP file, as well:
$errors = array();
$data = array();
// Getting posted data and decodeing json
$_POST = json_decode(file_get_contents('php://input'), true);
// checking for blank values.
if (empty($_POST['email']))
$errors['email'] = 'E-Mail erforderlich.';
if (!empty($errors)) {
$data['errors'] = $errors;
} else {
$data['message'] = 'The data should now be inserted into database!';
}
// response back.
echo json_encode($data);
?>
EDIT 1.
The event is triggered in Dev Tools - Network.
This is what I get:
Request URL: http://localhost:63342/url-to/emailInsert.php
Request method: POST
Remote address: 127.0.0.1:63342
Status code: 200 OK
Version HTTP/1.1
The page is not reloading on submit, at all, there is no error in Dev Tools - Console. It gives a OK status even though the email has not been ineserted into input, therefore it should print an error, which it doesn't do.
Any help is greatly appreciated.