AngularJS Login form with ng-click not working - angularjs

I wrote a basic login form in this plunk http://plnkr.co/edit/xQEN1ZNN5ZEw1CSwNw97?p=preview (click on the red Log into Dashboard button on the Home route).
However for some reason I cannot get the login() method to fire in my loginCtrl controller code.
Why is this example working, and mine is not ? http://plnkr.co/edit/H4SVl6?p=preview
Instead what it's doing is an old-school URL redirect with the user/password parameters passed in as form variables. I can't figure out what's wrong.
Here is LoginCtrl code as well as the login-form.html template :
(function () {
'use strict';
angular.module('routerApp').controller('LoginCtrl',
['$rootScope', '$scope', authenticate]);
function authenticate($rootScope, $scope, userService) {
var login = this;
login.loginUser = function () {
login.dataLoading = true;
//loginService.authUser(login.user, login.password); // TO DO !!!
};
login.test = function () {
var test = true;
};
}
})();
<div ng-show="error" class="alert alert-danger">{{error}}</div>
<form ng-submit="login.loginUser()" name="form">
<div class="form-group">
<label for="username">Username</label>
<i class="fa fa-key"></i>
<input type="text" name="username" id="username" class="form-control" ng-model="login.username" required />
<span ng-show="form.username.$dirty && form.username.$error.required" class="help-block">Username is required</span>
</div>
<div class="form-group">
<label for="password">Password</label>
<i class="fa fa-lock"></i>
<input type="password" name="password" id="password" class="form-control" ng-model="login.password" required />
<span ng-show="form.password.$dirty && form.password.$error.required" class="help-block">Password is required</span>
</div>
<div class="form-actions">
<button type="submit" ng-disabled="form.$invalid || dataLoading" class="btn btn-danger">Login</button>
<img ng-if="login.dataLoading" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA=="/>
</div>
</form>
In my local app, it is posting the old-style form variables via the URL, and I cannot get it to fire the login.loginUser function below inside LoginCtrl.
thnk you in advance...
Bob

for some odd reason (perhaps ui-router versioning) the controllerAs is not working.
Diana´s answer is valid, but it doesn´t use the controlleras syntax.
If you still want to use it, change the ui-router setting to:
.state('login', {
url: "/login",
templateUrl: "login-form.html",
controller: 'LoginCtrl as login',
})
That should do the trick ;)
Check it out:
http://plnkr.co/edit/OCqNexVeFFxt4kUuEVc1?p=preview

The controller change I applied is:
angular.module('routerApp').controller('LoginCtrl', function ($rootScope, $scope) {
$scope.loginUser = function () {
$scope.dataLoading = true;
//loginService.authUser(login.user, login.password); // TO DO !!!
};
$scope.test = function () {
var test = true;
};
})
and in the template I removed login. from the ng-if and ng-submit.
Here is a working plunks.

Related

Post angularjs form to nodejs Express ( Bad request)

im new in angularJs, im trying to make a basic login with angularJS and nodejs ( server side), i dont care about security for now im just trying to learn how to post. so i made a login form and a controller with angular :
My Login Form :
<div class="col-md-4">
<h1>Login</h2>
<form class="form" >
<div class="form-group">
<label>Username</label>
<input type="email" class="form-control" ng-model="login.mail" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" ng-model="login.password" required>
</div>
<div>
<button type="text" class="btn btn-default" ng-click="login()">Login</button>
</div>
</form>
</div>
then my router & controller Angularjs :
'use strict';
angular.module('login', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {
templateUrl: 'views/login.html',
controller: 'loginCtrl'
});
}])
.controller('loginCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.login = function() {
$http.post('/api/users/login', $scope.login).success(function (response) {
console.log(response);
// refresh();
});
};
}]);
and Server side i have that :
router.post('/login/', function(req, res) {
// here "/login/" means "/users/login" ( in index of controllers)
console.log(req.body.mail);
var usermail = req.body.mail;
var pass = req.body.password;
console.log(usermail + pass);
User.find({mail: usermail}, function(err, user) {
if (err) {
res.send(err);
console.log("ça marche pas")
} else {
res.json( user );
console.log(user);
}
})
});
server side : it works ( when i use DHC chrome extension to Post) but when im using angularjs view i got that error :
POST http://localhost:3000/api/users/login 400 (Bad Request)
Please help me to solve that, i think i missed something. Thank you in advance.
I think you are sending your login function as in below line:
$http.post('/api/users/login', $scope.login)
You probably want to pass a parameter in your login function that can be sent to server as below:
$scope.login = function(loginData) {
$http.post('/api/users/login', loginData).success(function (response)
Update
You are assigning your form values to $scope.login. If you would create a separate variable for it, for example loginForm, you can send this as valid JSON to your API:
<div class="col-md-4">
<h1>Login</h2>
<form class="form" >
<div class="form-group">
<label>Username</label>
<input type="email" class="form-control" ng-model="loginForm.mail" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" ng-model="loginData.password" required>
</div>
<div>
<button type="text" class="btn btn-default" ng-click="login(loginData)">Login</button>
</div>
</form>
</div>
And .js:
.controller('loginCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.loginForm = {
mail: '',
password: ''
};
$scope.login = function(loginData) {
// Check what this prints out:
console.log(loginData);
$http.post('/api/users/login', loginData).success(function (response) {
console.log(response);
// refresh();
});
};
}]);

angularjs and ui-router - controller not working

The full source code.
I don't understand why $scope not working in my LoginGuideCtrl controller. I try click on login button and should show a <p> with new data but the $scope is not updating...
Don´t forget I'm trying to achieve a modular design.
I have the following code:
guides.js
var guides = angular.module('main.guides', ['ui.router']).config(function ($stateProvider) {
$stateProvider.
state('guides.login', {
url: '/login',
templateUrl: 'modules/guides/views/login.html',
controller: 'LoginGuideCtrl'
}).
...
state('guides.mobile', {
url: '/web',
template: '<div>guildes mobile</div>',
controller: 'ListCtrl'
});
});
controller.js
var guides = angular.module('main.guides');
guides.controller('IndexCtrl', function() {
console.log('Index');
})
.controller('LoginGuideCtrl', function($scope) {
console.log('feck');
$scope.checkLogin = function(){
$scope.message = "Welcome "+$scope.name+"!"
};
})
.controller('ListCtrl', function() {
console.log('List');
})
login.html
<div class="form-group col-sm-2">
<label for="usr">Name:</label>
<input type="text" class="form-control" id="usr" ng-model="name">
</div>
<div class="form-group col-sm-2">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" ng-model="password">
</div>
<button type="button" class="btn btn-default" ng-click="checkLogin()">Login</button>
<p ng-model="message"></p>
ng-model is used with <input> tags to capture user input, by two way binding with your model value.
Since a <p> tag does not collect user input, it won't work with ng-model. Instead just do a one way binding with the value using the curly brackets:
<p>{{message}}</p>

AngularJS error: TypeError: v2.login is not a function

I would like to call the login function when I click the login button but keep getting the error message in the title. Can someone point out the error in my script?
login.js code below:
/*global Firebase, angular, console*/
'use strict';
// Create a new app with the AngularFire module
var app = angular.module("runsheetApp");
app.controller("AuthCtrl", function ($scope, $firebaseAuth) {
var ref = new Firebase("https://xxxxx.firebaseio.com");
function login() {
ref.authWithPassword({
email : "xxxxx",
password : "xxxx"
}, function (error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
And the code for login.html is also below:
<div class="container" style="max-width: 300px">
<form class="form-signin">
<h2 class="form-signin-heading" style="text-align: center">Please Sign In</h2>
<input type="text" class="form-control" name="username" ng-model = "username" placeholder="Email Address" required="" autofocus="" />
</br>
<input type="password" class="form-control" name="password" ng-model = "password" placeholder="Password" required=""/>
</br>
<button class="btn btn-lg btn-primary btn-block" type="submit" ng-click="login()">Login</button>
</form>
</div>
Edge case here, but I want to mention it for posterities' sake. I got this same error when using the controllerAs pattern with a form name with the same value as ng-submit. For example:
<form name="authCtrl.signUp" ng-submit="authCtrl.signUp()">
Throws: TypeError: v2.signUp is not a function
The solution was to change the name of the form to something different:
<form name="authCtrl.signUpForm" ng-submit="authCtrl.signUp()">
In my case, I was having an exact same issue as yours. However, coming across gkalpak's answer to such a scenario helped me out.
Turned out to be what I was calling was addBuddy() function, from a form named "addBuddy". The solution was to change the name of either of the two things to make one stand out or differentiable from the other. I changed the name of the form to "addBuddyForm" and voila! My function worked!
Here's a snippet of my case:
<form name="addBuddy" class="form-horizontal" novalidate>
...
<button class="btn btn-sm btn-info" ng-click="addBuddy()>Submit</button>
Which, I changed to:
<form name="addBuddyForm" class="form-horizontal" novalidate>
...
<button class="btn btn-sm btn-info" ng-click="addBuddy()>Submit</button>
...and it worked! :)
In AngularJS call the function from view it must be in the $scope.
JS
// exposes login function in scope
$scope.login = login;
HTML
<div class="container" ng-controller="AuthCtrl" style="max-width: 300px"> <!-- I notice here for include ng-controller to your main div -->
<form class="form-signin">
<h2 class="form-signin-heading" style="text-align: center">Please Sign In</h2>
<input type="text" class="form-control" name="username" ng-model = "username" placeholder="Email Address" required="" autofocus="" />
</br>
<input type="password" class="form-control" name="password" ng-model = "password" placeholder="Password" required=""/>
</br>
<button class="btn btn-lg btn-primary btn-block" type="submit" ng-click="login()">Login</button>
</form>
This may not be specific to your problem, but I was also getting this error and it took a bit to figure out why.
I had named both a function and a variable the same, with the variable assigned in the function, and so the assignment of the variable was overriding the function and it was exploding on a second run.
You'll notice in the example the uploadFile() function as an upload.uploadFile = true; This was a wonderful file that was meant to be upload.uploadingFile - a flag used to control the behavior of a spinner. Once that was fixed, the issue went away.
Example:
(function()
{
'use strict';
angular.module('aumApp.file-upload')
.controller('FileUploadCtrl', FileUploadCtrl);
function FileUploadCtrl($scope, $http)
{
upload.uploadFile = function()
{
upload.uploadFile = true;
var backendUrl = '/ua_aumcore/events/api/v1/events/uploadFile';
var fd = new FormData();
fd.append('file', upload.src);
$http({ url: backendUrl, data: fd, method: 'POST', transformRequest : angular.identity, headers: { 'Content-Type' : undefined } })
.then(function uploadSuccess(response)
{
upload.data = response.data;
upload.message = "Uploaded Succesfully.";
upload.uploadSuccess = true;
upload.uploadingFile = false;
},
function uploadFailure(response)
{
upload.message = "Upload Failed.";
upload.uploadSuccess = false;
upload.uploadingFile = false;
});
};
}
FileUploadCtrl.$inject = ['$scope', '$http'];
})();
To be callable from the view, a function must be in the $scope. Add
$scope.login = login;
to the JS code of the controller.
You also need to actually use that controller. Change
<div class="container" style="max-width: 300px">
to
<div ng-controller="AuthCtrl" class="container" style="max-width: 300px">
This is all fundamental stuff. My advice would be to learn from an AngularJS tutorial before going further.
Two enable two-way binding you have to assign your login function to $scope. Replace your code for function with this:
$scope.login=function() {
ref.authWithPassword({
email : "nick.koulias#gmail.com",
password : "Jaeger01"
}, function (error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
});
}
It may be a late answer by me.
But It working for me
Check form name you set
e.g. ng-form="login"
and function name
e.g. ng-click="login()"
Then it will not work . You have to change one of them.
e.g. ng-form="loginForm"
Explanation:
AngularJS 1.x registers any form DOM element that has a name property in $scope via formDirectiveFactory. This directive automatically instantiates form.FormController if the above is true:
If the name attribute is specified, the form controller is published onto the current scope under
from: angular.js:24855
Hence if you have a <form name=myForm> it will override your $scope.myForm = function() { ... }

What is wrong in this binding?

I have an angular ui-grid in which data is displayed and in every row there is an "Edit" and "Delete" button. When the user clicks on the "Edit" then a modal window is displayed and the fields are populated and the user can edit the data. This is the user scenario I have. When the user clicks on the "Edit" button I pass through the id value and when angular creates the modal window I query the data from the server.
As you can see in the html the controller is not bound because it is managed by another controller. If it would be bound here then it would be called twice.
The fields are populated properly and when I change something in it and I want to save it then breeze says that nothing has changed in the entity and the log in the save method gives back the original values of the entity.
I assume something is wrong with the data binding but I don't know what.
According to the pluralsight video and breeze's documentation breeze tracks the changes in the entity.
What I'm doing wrong?
The form:
<form class="form-horizontal" name="editModuleModalForm">
<legend>Edit module</legend>
<div class="control-group">
<label class="control-label">Module name</label>
<div class="controls">
<input type="text"
placeholder="Module name here..."
data-ng-model="vm.sysmodule.name"
data-z-validate />
</div>
</div>
<div class="control-group">
<label class="control-label">Module Sort number</label>
<div class="controls">
<input type="text"
placeholder="Module sort number"
data-ng-model="vm.sysmodule.sortNo"
data-z-validate />
</div>
</div>
<div class="control-group">
<label class="control-label">Route</label>
<div class="controls">
<input type="text"
placeholder="Module route comes here..."
data-ng-model="vm.sysmodule.route"
value="vm.sysmodule.route"
data-z-validate />
</div>
</div>
<div class="control-group">
<button type="submit" class="btn btn-success" data-ng-click="vm.save()">Save</button>
<button type="submit" class="btn btn-danger" data-ng-click="vm.cancel()">Cancel</button>
</div>
</form>
Angular controller for the form
(function () {
'use strict';
var controllerId = 'editModuleController';
angular
.module('dilibApp')
.controller(controllerId, ['$scope', '$modalInstance', 'selectedModuleId', 'common', 'datacontext', editModuleController]);
function editModuleController($scope, $modalInstance, selectedModuleId, common, datacontext) {
/* jshint validthis:true */
var vm = this;
vm.title = 'editModule';
vm.sysmodule = undefined;
vm.cancel = cancel;
vm.save = save;
activate();
function activate() {
onDestroy();
common.activateController([getModulePropertiesToBeEdited()], controllerId);
}
function getModulePropertiesToBeEdited() {
return datacontext.sysmodule.getById(selectedModuleId)
.then(function (result) {
vm.sysmodule = result[0];
});
}
function onDestroy() {
$scope.$on('$destroy', function () {
datacontext.cancel();
});
}
function cancel() {
$modalInstance.dismiss('cancel');
}
function save() {
console.log(vm.sysmodule);
if (datacontext.hasChanges) {
datacontext.saveChanges();
console.log('Changes are saved!');
} else {
console.log('There are no changes to be saved!');
}
$modalInstance.close();
}
}
})();
Nothing is wrong with the binding. The root if the problem is that the datacontext doesn't have hasChanges method due to that the breeze's entityManager is wrapped in it. I had to rework the code a little bit, rethinking the responsibilities and it is working now.

firebaseSimpleLogin: $createUser Promise Not Resolving until Another Event Occurs

I'm setting up registration/login functionality using angular, Firebase, and firebaseSimpleLogin. After reading over a few tutorials and another Stack Overflow thread, I've got the registration working with one small but important caveat: the promise on the SimpleLogin $createUser function isn't resolving until I click on a link or button on my html page. Here's my code:
Register.html
<div class="form-group" >
<label class="control-label" for="email">Email</label>
<input class="form-control" type="text" name="email" id="email" ng-model="cred.email"/>
<label class="control-label" for="password">Password</label>
<div class="form-group">
<input class="form-control" type="password" name="password" id="password" ng-model="cred.password"/>
</div>
<div class="form-group">
<input type="submit" value="Register" class="btn btn-primary" ng-click="register()"/>
</div>
</div>
Main.Js
angular.module('myApp')
.controller('AuthCtrl',
['$scope',
'$location',
'$firebase',
'$firebaseSimpleLogin',
'loginService',
function AuthCtrl($scope, $location, $firebase, $firebaseSimpleLogin,
loginService) {
$scope.register = function(){
var user = {
email: $scope.cred.email,
password: $scope.cred.password
};
loginService.register(user);
};
});
loginService.js (note FBURL is defined elsewhere)
angular.module('myApp')
.factory('loginService', function($firebaseSimpleLogin, $rootScope, $location,
$timeout) {
var ref = new Firebase(FBURL);
var auth = $firebaseSimpleLogin(ref);
return {
register: function (user) {
return auth.$createUser(user.email, user.password)
.then(function(registeredUser) {
console.log(registeredUser);
}
)}
});
In the above loginService.js, I'm not seeing the console.log until I click a button or element; however, the user is created in the Firebase Simple Login DB when I look online. As soon as I click a button or element, the console.log shows. My guess as to the issue is that the promise from auth.$createUser() isn't getting resolved, but I cannot find out why that would be.

Resources