Login in angularjs - angularjs

I have an idea of how to use post method for login, however, our new requirement is my API team has provided get method. How is this used in angular? Please help me. I am stuck on this problem as I am new to angular. Below is the API for get method:
http://183.82.48/HospitalManagementSystem/Service1.svc/LoginVerification/{EMAILID}/{PASSWORD}

You can try to construct the URI yourself.
<form ng-app="login" ng-controller="loginCtrl">
<span>Email</span><input ng-model="emailId" type="text" required><br>
<span>Password</span><input ng-model="password" type="password" required><br>
<button ng-click="login()">Login</button>
</form>
<script>
var app = angular.module('login', []);
app.controller('loginCtrl', function($scope, $http) {
$scope.login = function() {
$http.get('http://183.82.0.48/HospitalManagementSystem/Service1.svc/LoginVerification/' + $scope.emailId + '/' + $scope.password).then(
function (response) {
console.log(response.data);
// ...
},
function (error) {
console.log(error);
// ...
}
)
}
});
</script>

Related

Angular 1.5 - Clear form after submit

I have read through all of the suggested postings on this, but I can't seem to clear the form fields after I submit.
I am using controller as syntax, but even if I try to use $scope with $setPristine, I still can't make it work.
This SO answer is what I am following:
https://stackoverflow.com/a/37234363/2062075
When I try to copy this code, nothing happens. No errors, nothing is cleared.
Here is my code:
app.controller('HiringRequestCtrl', function ($http) {
var vm = this; //empty object
vm.ctrl = {};
vm.saveChanges = function() {
//console.log(vm);
$http({
method: 'POST',
url: '/hiringrequest/createPost',
data: angular.toJson(vm)
})
.success(function (response) {
//great, now reset the form
vm.ctrl = {};
})
.error(function (errorResponse) {
});
}
});
and my form looks like this:
<div ng-controller="HiringRequestCtrl as ctrl">
<form id="form" name="ctrl.myForm">
...
<input type="text" name="proposalName" ng-model="ctrl.proposalName"/>
<input type="submit" id="saveButton" value="Submit" class="button" ng-click="ctrl.saveChanges()" />
...
</form>
</div>
I would really prefer not to use $scope.
There's some fundamental issues with the way you've structured this. I think your use of vm.ctrl and then also ng-controller="HiringRequestCtrl as ctrl" is confusing you. Below are my recommended [untested] changes. (I would also suggest moving the $http stuff into a service and using .then() and .catch() because .success() and .error() are deprecated).
Controller
.controller('HiringRequestCtrl', function($http) {
var vm = this; // self-referencing local variable required for when promise resolves
vm.model = {};
vm.saveChanges = function() {
$http({
method: 'POST',
url: '/hiringrequest/createPost',
data: angular.toJson(vm.model)
})
.success(function(response) {
//great, now reset the form
vm.model = {}; // this resets the model
vm.myForm.$setPristine(); // this resets the form itself
})
.error(function(errorResponse) {});
}
});
HTML
<div ng-controller="HiringRequestCtrl as ctrl">
<form id="form" name="ctrl.myForm" ng-submit="ctrl.saveChanges()" novalidate>
<input type="text" name="proposalName" ng-model="ctrl.model.proposalName" />
<input type="submit" id="saveButton" value="Submit" class="button" />
</form>
</div>
Update
Service
.service('hiringService', function($http) {
var service = {};
service.createPost = function(model) {
return $http({
method: 'POST',
url: '/hiringrequest/createPost',
data: angular.toJson(model)
});
}
return service;
}
Controller
.controller('HiringRequestCtrl', function(hiringService) {
vm.saveChanges = function() {
hiringService.createPost(model)
.then(function(response) {
// if you need to work with the returned data access using response.data
vm.model = {}; // this resets the model
vm.myForm.$setPristine(); // this resets the form itself
})
.catch(function(error) {
// handle errors
});
}

Why isn't the form sending the text value from my form?

I'm following a tutorial to create a simple todo app using the MEAN stack. Everything was working fine until I moved the controllers and services into separate files. Now I can create a new todo but it doesn't get the text value. I can see in my mongoDB database that a new entry has been created but it doesn't have a text value. I've been looking all over my code but I can't find anything nor do I get any error or warnings in the developer tools of the browser.
Here is the code for the form:
<div id="todo-form" class="row">
<div class="col-sm-8 col-sm-offset-2 text-center">
<form>
<div class="form-group">
<!-- Bind this value to formData.text in Angular -->
<input type="text" class="form-control input-lg text-center" placeholder="Add a todo" ng-model="formData.text">
</div>
<button type="submit" class="btn btn-primary btn-lg" ng-click="createTodo()">Add</button>
</form>
</div>
</div>
Here is my service:
//todos.js service
//the service is meant to interact with our api
angular.module('todoService', [])
//simple service
//each function returns a promise object
.factory('Todos', function($http){
return {
get : function() {
return $http.get('/api/todos');
},
create : function(todoData){
return $http.post('/api/todos', todoData);
},
delete : function(id){
return $http.delete('/api/todos/' + id);
}
}
});
Here is my main controller which uses the service:
//main.js
var myApp = angular.module('todoController', []);
myApp.controller('mainController', ['$scope', '$http', 'Todos', function($scope, $http, Todos){
$scope.formData = {};
//GET
//get all the todos by using the service we created
Todos.get()
.success(function(data){
$scope.todos = data;
});
//CREATE
$scope.createTodo = function(){
Todos.create($scope.formData)
.success(function(data){
$scope.formData = {};
$scope.todos = data;
});
}
//DELETE
$scope.deleteTodo = function(id){
Todos.delete(id)
.success(function(data){
$scope.todos = data;
});
};
}]);
Lastly, here is the route for creating a todo:
var Todo = require('./models/todos');
//expose our routes to our app with module exports
module.exports = function(app){
//api
//get all todos
app.get('/api/todos', function(req, res){
Todo.find(function(err, todos){
if(err)
res.send(err);
res.json(todos);
});
});
//create to do
app.post('/api/todos', function(req, res){
Todo.create({
text: req.body.text,
done: false
}, function(err, todo){
if(err)
res.send(err);
//get and return all todos after creating the new one
Todo.find(function(err, todos){
if(err)
res.send(err);
res.json(todos);
});
});
});
To recap, for some reason the formData.text value doesn't get stored somewhere and I don't know why.
I can't say for sure with angular but normal HTML forms inputs need a name attribute to submit

Unable to Pass Variable from controller to service in AngularJS

I'm trying to pass a zip code to a service that runs an API call using this zip. The problem is, every time I enter a zip and search, the zip code is not passed to the service properly and my HTTP request sends with the zip code as undefined.
Here is my controller:
angular.module('MainCtrl', []).controller('MainController', ['$scope', 'Reps', function($scope, Reps) {
$scope.search = function() {
Reps.search($scope.zipCode)
.success(function(response) {
console.log('Success ' + response);
})
.failure(function(response) {
console.log('Failure ' + response);
})
}
}]);
My service:
angular.module('MainService', []).factory('Reps', ['$http', function($http) {
var root = 'https://www.api.com/locate?';
var apiKey = '&apikey=foo';
var fields = '&fields=bar';
return {
search: function(zipCode) {
var query = root + zipCode + apiKey + fields;
return $http({
method: 'POST',
url: query
})
}
}
}])
My form:
<form method="post" enctype="text/plain" class="form-inline">
<div class="form-group">
<label for="searchForRep">Zip Code:</label>
<input type="text" class="form-control" id="searchForRep" ng-model="zipCode" placeholder="Zip Code (11216)">
</div>
<button ui-sref="reps" ng-click="search()" type="submit" class="btn btn-default">Submit</button>
</form>
So, as mentioned, the zip code does not seem to pass to my service correctly, which is causing the HTTP request to send as:
https://www.api.com/locate?undefined&apikey=foo&fields=bar
Any idea what the issue is with my code?
As per your code it should work. It is working on my plunker, except you did not add your service module to your controller module like:
angular.module('MainCtrl', ['MainService']).controller('MainController',
Plunker here: http://plnkr.co/edit/Ey3K5eF5h56dqWTji5uX?p=preview

Angularjs checkbox initialization issue using json object

So i have a checkbox page barely working, the issue is when i first start this page, the checkbox is not checked, even though i try to initialize it from backend node server. No error in browser debugger though.
in the server mye,
app.get('/2getMyDiagValue', function(req, res)
{
console.log("get my diag");
var formDataArray = { "formDataObjects": [
{"flagName":"myStuff1", "flagVal":0},
{"flagName":"myStuff2", "flagVal":1}
]};
res.contentType('application/json');
res.send(formDataArray);
});
app.post('/2setMyDiagValue', function(req, res)
{
......
}
in the client mye,
app.controller('myDiagController', function($scope, $http, $routeParams, QueryMyService) {
$scope.message = 'SID Diagnostics';
// using http.get() to get existing my setting from server mye
QueryMyService.getInfoFromUrl7('/2getMyDiagValue').then(function(result) {
$scope.formData = result.formDataObjects;
}, function(error) {
alert("Error");
} );
$scope.submitForm = function() {
console.log("posting form data ...");
$http.post("/2setMyDiagValue",
JSON.stringify($scope.formData)).success(function(){} );
};
});
app.factory('QueryMyService', function($http, $q, $location) {
var factory = {};
var browserProtocol = 'http';
var port = ':1234';
var address = 'localhost';
var server = browserProtocol + '://' + address;
//////////////////////////////////////////////////////////
factory.getInfoFromUrl7 = function(myUrl) {
var deferred = $q.defer();
$http.get(myUrl).success(function(data) {
deferred.resolve(data);
}).error(function(){
deferred.reject();
});
return deferred.promise;
}
return factory;
}
checkbox webpage itself
<form ng-submit="submitForm()" ng-controller="myDiagController">
<div class="control-group" style="color:black">
<label>My Checkbox</label>
<div class="checkbox">
<label class="checbox-inline" >
<input class="big-checkbox" type="checkbox" ng-model="formData.myStuff1"
ng-true-value="1" ng-false-value="0" ng-checked="formData.myStuff1 == 1">
<h4>Message 1</h4>
<input class="big-checkbox" type="checkbox" ng-model="formData.myStuff2"
ng-true-value="1" ng-false-value="0" ng-checked="formData.myStuff2 == 1">
<h4>Message 2</h4>
</label>
</div>
<br>
<input class="btn-primary" type="submit">
</form>
i did try to modify ng-checked like this and the checkbox did show checked.
ng-checked="true"
well, just used "res.json" in the node.js side and made it work, guess i just don't have time to learn, while this fxxking company gave me a tough schedule

Form data always going null for text field in angular js and rest service spring

I am new to AngularJS and not sure where I am missing, though I know its a minor mistake which I am committing. Please help me out with below scenario.
I have a form where in I write a post {textArea} and click submit button, which calls ng-click=createPost() method.
It goes to controller.js which is:
app.controller('MyCtrl1', ['$scope', 'PostFactory', '$location', function ($scope, PostFactory, $location) {
/* callback for ng-click 'createUser': */
$scope.createPost = function() {
alert("in createPost" + $scope.post.postText);
alert("in createPost" + $scope.post);
PostFactory.create($scope.post)
$scope.posts.push($scope.post.postText);
$scope.post = "";
$location.path('/view1');
}
$scope.posts = PostFactory.query();
/*UserFactory.get({}, function (userFactory) {
$scope.firstname = userFactory.firstName;
})*/
}]);
and my service.js is:
var services = angular.module('ngdemo.services', ['ngResource']);
//alert("In services");
services.factory('PostFactory', function ($resource) {
// alert("Reached services.js");
return $resource('/ngdemo/web/posts', {}, {
query: {
method: 'GET',
//params: {},
isArray: true
},
create: {method: 'POST'}
})
});
my Spring controller which is exposed as service and have post method:
#RequestMapping(/*value = "/add",*/ method = RequestMethod.POST)
public #ResponseBody String addPost(#ModelAttribute(value = "") Post post, BindingResult result) {
System.out.println("Post value : " + post.getPostText());
//post.setPostId();
post.setPostTags("#dummy");
postService.addPost(post);
return "redirect:/";
}
my form :
<form novalidate="novalidate" class="form-horizontal">
<!-- Textarea -->
<div class="form-group">
<div class="col-md-4">
<textarea ng-model="post.postText" rows="4" cols="300" name="inputQuestion" id="post.postText" class="form-control expand" placeholder="What you want to pingle today?"></textarea>
</div>
<br>
<!-- Button -->
<div class="col-md-4">
<button ng-click='createPost()' class="btn btn-default plus"> Pingle it! </button>
</div>
</div>
</form>
Problem is : always Post value in controller is coming as null, have tried with $scope.post and $scope.postText but no joy!
Please let me know where I am missing?????
UPDATE:
How can we pass a form object to Spring Controller in controller.js?? Post is my Domain object
it worked, once I replaced #ModelAttribute with #RequestBody, somehow it was preventing the data to be populated in my object. After setting #RequestBody, it worked!Thanks all!

Resources