I am using a form in html, using angular, and binding the username and email id of the user.
I wish to display the details of the particular user onto a server page, where in when a user clicks on Submit details on the front end, the data is "binded" and the information is simultaneously shown on the server page.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<title>Random title here</title>
<body ng-app="test" ng-controller="mainctrl as ctrl">
<div class="container">
<div class="col-sm-8 col-sm-offset-2">
<form name="userform" ng-submit="ctrl.submit()">
<div class="form-group">
<label> Name</label>
<input type="text" name="name" class="form-ctrl" ng-model="ctrl.user.name">
</div>
<div class="form-group">
<label> Email id</label>
<input type="email" name="email" class="form-ctrl" ng-model="user.email">
</div>
<button type="submit" class="btn btn-primary"> Submit </button>
</form>
</div>
</div>
<script>
var test=angular.module('test',[]);
test.controller('mainctrl',[function($scope,$html){
$scope.user={};
$scope.submit= function () {
$http({
method : 'POST',
url : 'test1.java', //No idea what to put here. Help pls.
data : $scope.user;
headers : {'Content-Type':'application/x-www-form-urlencoded'}
}).success(function(data)
{
console.log("Success");
});
}
}]);
</script>
</body>
</html>
This is just a sample of code I typed. As a beginner, any help would be appreciated. Thanks.
If you are using controller as syntax than you should write your function with reference this. Your controller snippet would be like
angular.module('test',[])
.controller('mainctrl',[function($scope, $http){
var cm = this;
cm.user={};
cm.submit= function () {
$http({
method : 'POST',
url : form.attributes['target'],
data : cm.user;
}).success(function(data)
{
console.log("Success");
});
}
}]);
and pass the form element in your ng-submit directive. Like
<form name="userform" ng-submit="ctrl.submit($element.action)">
I hope my code will be usefull for you!
View:
<body ng-controller="UserDataController">
<form ng-submit="sendData(user)">
<input type="text" placeholder="name" ng-model="user.name" />
<input type="text" placeholder="second name" ng-model="user.second_name" />
<button type="submit" class="btn btn-sm btn-primary">
Save
</button>
</form >
Cotroller:
angular.module('httpExample', [])
.controller('UserDataController', ['$scope', '$http', function($scope, $http) {
$scope.user = {};
$scope.sendData= function(user) {
$http.post("/SomeUrl", user).success(function(data, status) {
console.log(data);
console.log(status);
$scope.data = data;
// now you can write {{data}} at your veiw
// example {{data.id}}
});
}]);
Example: get request
Related
I am trying to learn angularjs.I wan't to share data between two controllers of two different pages. After googling came to know about services and created one service. From one page I am able to call my rest service and able to get data. After I am trying to redirect to different page. URL is changing but page is not loaded. Stuck here. Please find the code below. Anybody can help me where I am doing wrong?
data.html
<!DOCTYPE html>
<html>
<head>
<base href="/">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular-resource.min.js"></script>
<script src="app.js"></script>
<script src="usercontroller.js"></script>
<script src="userservice.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="UserController" >
<form>
<input type="text" name="Name" ng-model="user.userName"> Name <br/>
<input type="text" name="password" ng-model="user.password"> Password <br/>
<button type="submit" ng-click="getUser(user)" >Submit</button>
</form>
data2.html
<!DOCTYPE html>
<html>
<head>
<base href="/">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.js"></script>
<script src="app.js"></script>
<script src="usercontroller.js"></script>
<script src="userservice.js"></script>
</head>
<body>
<div ng-controller="UserController2" >
<form>
<input type="text" name="Name" ng-model="user.userName"> Name <br/>
<input type="text" name="password" ng-model="user.password"> Password <br/>
<button type="submit" ng-click="shareUser()" >Submit</button>
</form>
</div>
app.js
var App = angular.module('myApp',['ngRoute','ngResource']);
App.config(['$routeProvider',
function (
$routeProvider
) {
$routeProvider.
when('/home', {
templateUrl: 'data.html',
controller: 'UserController'
}).
when('/welcome', {
templateUrl: '/data2.html',
controller: 'UserController2'
}).
otherwise({
redirectTo: '/home'
});
}]);
usercontroller.js
App.controller('UserController', ['$scope', 'UserService', '$window', function($scope, UserService,$window,$location) {
alert("inside user controller");
var self = this;
$scope.user={};
$scope.user.userName="murali";
$scope.user.password="murali123";
$scope.getUser = function(user){
alert("inside function");
UserService.getUser(user).then(function(data){
alert("data::"+JSON.stringify(data.userName));
$window.location.href ='/welcome';
});
};
}]);
App.controller('UserController2', ['$scope', 'UserService', function($scope, UserService) {
alert("inside user controller");
$scope.user={};
$scope.findUser = function(){
alert("inside function");
$scope.user = UserService.findUser();
alert("userName::"+$scope.user.userName);
};
}]);
userservice.js
App.factory('UserService', ['$http', '$q', function($http, $q){
var user = {};
return {
getUser : function(user){
return $http.post('http://localhost:8080/user/login', angular.toJson(user))
.then(
function(response){
alert(JSON.stringify(response.data));
user=response.data;
return response.data;
},
function(errResponse){
console.error('Error while getting response');
return $q.reject(errResponse);
}
);
},
shareUser : function(){
return user;
}
};
}]);
If you redirect the entire page is reloaded and the service is created from 0, no data is saved, unless you store it in cookie or local/session storage. But I see you are using angular-route, so, you can still get it done.
First, when using angular-route, the views does not need to be a full html doc and instead just a piece of it. Example:
index.html
<!DOCTYPE html>
<html>
<head>
<base href="/">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"> </script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.js"></script>
<script src="app.js"></script>
<script src="usercontroller.js"></script>
<script src="userservice.js"></script>
</head>
<body>
<div ng-app="myApp">
<ng-view></ng-view> <!-- Required by angular-route -->
</div>
</body>
</html>
Please, note the <ng-view></ng-view> element, it is required by angular-route and is where the views will be loaded.
data.html
<form>
<input type="text" name="Name" ng-model="user.userName"> Name <br/>
<input type="text" name="password" ng-model="user.password"> Password <br/>
<button type="submit" ng-click="getUser(user)" >Submit</button>
</form>
data2.html
<form>
<input type="text" name="Name" ng-model="user.userName"> Name <br/>
<input type="text" name="password" ng-model="user.password"> Password <br/>
<button type="submit" ng-click="findUser()" >Submit</button>
</form>
Note that in data2.html I changed ng-click="shareUser()" to ng-click="findUser()" as UserController2 does not have a shareUser function.
Now, in UserController instead of using window.location.href ='/welcome'; use $location.path('/welcome');, this is what you need to use to navigate without reloading the entire page, angular-route will do the magic. You will need to add the $location service as a dependency.
In UserController2, change UserService.findUser(); to UserService.shareUser(); because UserService does not have a findUser function, and I think shareUser is what you are trying to use.
Also, take a look again to the $routeProvider configuration, '/data2.html' might be pointing to the wrong location.
And you are ready, reload the page and happy coding.
<form class="" ng-submit="submit()" ng-controller="MailingListController">
<input class="form-element large" placeholder="Email address" ng-model="emailaddress">
<input class="form-submit button large bkg-charcoal bkg-hover-pink color-white color-hover-white" type="submit" id="submit" value="Submit">
</form>
<script>
angular.module('ComingSoon', [])
.controller('MailingListController', ['$scope', function($scope) {
console.log("Working");
$scope.submit = function() {
console.log($scope.emailaddress);
};
}]);
</script>
I have tried to submit this form and the logs is showing there is nothing inside $scope.emailaddress. I have followed the documentation from angular website but it still doesn't work. Where isit that i am doing it wrongly?
Controller Binding to the view May gone wrong . you can take a look
here in the following plnkr
html :-
<!DOCTYPE html>
<html ng-app="ComingSoon">
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MailingListController">
<form class="" ng-submit="submit()">
<input class="form-element large" placeholder="Email address" ng-model="emailaddress">
<input class="form-submit button large bkg-charcoal bkg-hover-pink color-white color-hover-white" type="submit" id="submit" value="Submit">
</form>
</body>
</html>
controller :-
angular.module('ComingSoon', [])
.controller('MailingListController', ['$scope', function($scope) {
console.log("Working");
$scope.submit = function() {
console.log($scope.emailaddress);
};
}]);
Check you console while doing !!
https://plnkr.co/edit/B7aJhGKhXin1tsldljpz?p=preview
hi it is working for me
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="Scripts/angular.js"></script>
<script>
angular.module('ComingSoon', [])
.controller('MailingListController', ['$scope', function ($scope) {
console.log("Working");
$scope.submit = function () {
console.log($scope.emailaddress);
};
}]);
</script>
</head>
<body ng-app="ComingSoon">
<form class="" ng-submit="submit()" ng-controller="MailingListController">
<input class="form-element large" placeholder="Email address" ng-model="emailaddress">
<input class="form-submit button large bkg-charcoal bkg-hover-pink color-white color-hover-white" type="submit" id="submit" value="Submit">
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- <link rel="stylesheet" type="text/css" href="login.css"> -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-messages.min.js"></script>
</head>
<body ng-app="loginApp">
<div class="container">
<div class="login_logo">
</div>
<div class="form_container" ng-controller="loginCtrl" >
<div class="error_msg" ng-if="form_login.username.$dirty" ng-messages="form_login.username.$error">
<div class="alertmsg" ng-message="required">Username and password are required</div>
</div>
<div class="form_left">
<form class="form_login" name="form_login" ng-submit="submitForm()" novalidate>
<div class="usr"><input id="username" name="username" ng-model="username" type="text" autofocus="autofocus" required /></div>
<div class="psw"><input id="password" name="password" ng-model="password" type="password" required /></div>
</form>
</div>
<div class="form_right">
<a class="submit" href="" ng-click="submitForm()">submit</a>
</div>
<div class="clear"></div>
</div>
</div>
<script type="text/javascript">
var app=angular.module("loginApp",["ngMessages"]);
app.controller("loginCtrl", function($scope){
$scope.username = "";
$scope.password = "";
$scope.submitForm=function(){
};
});
</script>
</body>
</html>
Now I have a login page as it shows above, I'm trying to do the validation with ngMessages
If I have to use <a> which is outside of form to submit it instead of button, how should I do?
How can I make sure error messages are displayed when username or password is empty, and only after user submit the form.
How to prevent user from resubmitting form with <a>?
To show error messages only after form submit, add a variable '$scope.submitted = true;'.
In order to prevent re-submit submit button can be disabled.
Please refer following link for detailed explanation.
https://scotch.io/tutorials/angularjs-form-validation
Hope it helps.
You can check the validation result in your controller function with:
if ($scope.form_login.$valid) {
...
}
The form in angularjs will be validated auto. For all form members you can check the doc
I am new to angular js. please help me with the below issue
I have a form with a controller loginController. I have two text boxes user.email and user.password.
I want to post the data to servlet onclick of the Log in button.
I have written the following code, but when i click Log in, the data is not getting posted on to the server. Also there is no error message.
Below is my JSP file
`
<html ng-app="practiceApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link rel ="stylesheet" type="text/css" href="bootstrap.min.css"/>
</head>
<body>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="practice.js"></script>
<form name='login' ng-controller='loginController' ng-submit="login()">
<div>
{{hello}}
<label>Email</label>
<input type="email" name="email" ng-model="user.email" required/>
<span ng-show='login.email.$dirty && login.email.$error.required'>Required</span>
<span ng-show='login.email.$dirty && login.email.$error.email'>Not a valid email</span>
<label>Password</label>
<input type="password" name="password" ng-model="user.password" required/><br/>
<span ng-show='login.password.$dirty && login.password.$error.required'>Required</span>
<button ng-disabled="login.$invalid">Log in</button>
</div>
</form>
</body>
</html>
`
JavaScript File
`
var app = angular.module('practiceApp',[]);
app.controller('loginController',function($scope,$http){
$scope.login = function(){
$http({
method: 'POST',
url:'/login',
headers:{'Content-Type':'application/json'},
data:$scope.user
}).success(function(data){
$scope.status=data;
});
}
});
`
I have tried all the solutions that are available but couldn't find any result.. Kindly help on this
Your <button> does not cause the form to submit. Change to <input type="submit" ng-disabled="login.$invalid">Log in</button> or remove ng-submit from the form and add ng-click="login()" to the <button>.
I am creating an app to send an object to a class in Parse, but the data in the form is being passed and nothing happens. I can submit data directly from the function showAlert, but no alert appears after setNotification and and showALert is used. Here is my code:
<!doctype html>
<head>
<meta charset="utf-8">
<title>My Parse App</title>
<meta name="description" content="My Parse App">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/styles.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.18.min.js"></script>
</head>
<body>
<div id="main">
<h1>You're ready to use Parse!</h1>
<p>Read the documentation and start building your JavaScript app:</p>
<ul>
<li>Parse JavaScript Guide</li>
<li>Parse JavaScript API Documentation</li>
</ul>
<div style="display:none" class="error">
Looks like there was a problem saving the test object. Make sure you've set your application ID and javascript key correctly in the call to <code>Parse.initialize</code> in this file.
</div>
<div style="display:none" class="success">
<p>You're message has now been submited.'</p>
</div>
</div>
<div class="login">
<form class="login-form" name="login-form">
<h2>Compose Message</h2>
<input type="text" name="school" id="school" placeholder="School Code" />
<p> </p>
<input type="text" name="name" id="name" placeholder="Name" />
<p> </p>
<input type="text" name="password" id="password" placeholder="Message" />
<p> </p>
<input type="button" value="Set Notification" onClick="setMessage();">
<p> </p>
<input type="button" value="Send Notification" onClick="showAlert();">
</form>
</div>
<script type="text/javascript">
function setMessage (){
var textField = form.school.value
var textField1 = form.name.value
var textField2 = form.password.value
}
function showAlert() {
Parse.initialize("appkey", "javascript key");
var TestObject = Parse.Object.extend(textField);
var testObject = new TestObject();
testObject.save({teacher: textField1), message:textField2)}, {
success: function(object) {
$(".success").show();
alert('The Message has been sent!');
},
error: function(model, error) {
$(".error").show();
alert('There has been an error.');
}
});
}
</script>
</body>
</html>
I am dusting off my Javascript knowledge to create an page that syncs to an iOS app. Any help is greatly appreciated!