angularjs JavaScript inheritance, fail to bind data from view to a controller - javascript

what am trying to do is to get data from the form use it in my controller in HTTP post call but it's not working
I know i might have problem with inheritance of scopes but icant solve it.
here is my controller code:
.controller('SignUpCtrl', function($scope, $http, $state) {
$scope.submit = function() {
var url = 'http://localhost:3000/register';
var user = {
email: $scope.email,
password: $scope.password,
};
console.log($scope.user);
$http.post(url, user)
.success(function(res){
console.log('You are now Registered');
//$state.go('app.items');
})
.error(function(err){
console.log('Could not register');
// $state.go('error');
});
};
})
Here is the code of my Template:
<form name="register">
<div class="list">
<label class="item item-input no-border">
<input name="fullname" type="text" ng-model="fullname" placeholder="Full Name" required="">
</label>
<label class="item item-input">
<input name="email" type="email" ng-model="user.email" placeholder="Email" required="">
</label>
<p class="blue-font" ng-show="register.email.$dirty && register.email.$invalid">Please Write valid Email.</p>
<label class="item item-input">
<input name="password" type="password" ng-model="user.password" placeholder="Password" required="">
</label>
<button ng-click="submit();" ng-disabled="register.$invalid" type="submit" class="button signup-btn sharb-border white-font blue-bg-alt border-blue-alt ">
Sign Up
</button>
</div>
</form>
Note: i tried the ng-submit its not really the problem

Inside the controller.
.controller('SignUpCtrl', function($scope, $http, $state) {
$scope.user = {
email: '',
password: ''
};
$scope.submit = function() {
And this
var user = {
email: $scope.user.email,
password: $scope.user.password
};
Also drop the ; in ng-click
<button ng-click="submit()" ...>

Try to use rootScope (docs.angularjs.org/$rootScope").

Related

How to compare values in Angularjs?

I'm a newbie to angular, so I need a help.
In html, I wrote the following
<div class="form-group">
<input type="email" name="Email" id="LoginEmail class="form-control" placeholder="Email Address" required>
</div>
<div class="form-group">
<input type="password" name="password" id="LoginPassword" class="form-control" placeholder="Password" required>
</div>
In angular, I write the following code
angular
.module("LoginForm", [])
.controller("processingLoginForm", ["$scope", function ($scope) {
$scope.userinfo = [
{name : "User1",
account : "user1#whatever.com",
city: "XYZ",
password: "Angular#2017"}
];
}]);
I need to compare the value of input box with the value of the script and show a message if it's not correct, so how can I do that?
Firstly you need to assign model to your template scope. Use ng-model for this purpose. Then you need a form to submit and trigger a function to check if user input matches to the desired values.
Add ng-model and wrap your inputs with a form tag:
<form ng-submit="login()">
<div class="form-group">
<input ng-model="email" type="email" name="Email" id="LoginEmail" class="form-control" placeholder="Email Address" required>
</div>
<div class="form-group">
<input ng-model="password" type="password" name="password" id="LoginPassword" class="form-control" placeholder="Password" required>
</div>
<button type="submit">Login</button>
</form>
Check if user input is valid in Controller:
$scope.login = function() {
const isUserValid = $scope.email === $scope.userinfo[0].account && $scope.password === $scope.userinfo[0].password;
if(isUserValid) {
alert("Logged In Successfully");
}else {
alert("Email or password incorrect. Try again.")
}
}
Here's a working example of the above code.
In your input elements you miss the ng-model attribute. It is used to bind the values with your scope variables.
<input type="email" ... ng-model="email" ...>
<input type="password" ... ng-model="password" ...>
And in your controller you can write
if($scope.email == $scope.userinfo[0].account && $scope.password == $scope.userinfo[0].password){
//Login ok
}else{
//Login failed
}
Assuming there is a form element somewhere above
Add ng-submit to it
<form ng-submit="submit()">
Add ng-model to the form elements.
I have added state.email and state.password
<div class="form-group">
<input ng-model="state.email" type="email" name="Email" id="LoginEmail" class="form-control" placeholder="Email Address" required>
</div>
<div class="form-group">
<input ng-model="state.password" type="password" name="password" id="LoginPassword" class="form-control" placeholder="Password" required>
</div>
Compare the binding values to the values in $scope.userinfo
angular
.module("LoginForm", [])
.controller("processingLoginForm", ["$scope", function ($scope) {
$scope.userinfo = [{
name : "User1",
account : "user1#whatever.com",
city: "XYZ",
password: "Angular#2017"
}];
// when you submit the form, this function will be called
$scope.submit = function (e) {
e.preventDefault();
if ($scope.state.email !== $scope.userinfo[0].account || $scope.state.password !== $scope.userinfo[0].password) {
// did not match
} else {
// matched
}
}
}]);

ajax request is looping in Angularjs

Hi I am developing Angularjs application. I am making ajax call to server to get some details. Request is POST. Code written for Ajax is looping and it is not stopping.
(function () {
angular.module('RoslpApp').controller('ChangePassword', ['$scope', '$http', '$translatePartialLoader', '$translate', '$state', '$stateParams', 'cfg', 'toastr',
function ($scope, $http, $translatePartialLoader, $translate, $state, $stateParams, cfg, toastr) {
var url = cfg.Baseurl + "api/Customer/ResetPassword";
// alert(SomeFactory.getData());
var url = cfg.Baseurl + "api/Customer/ModifyPassword";
var ID = $stateParams.LoginID;
debugger;
//this loops and never stops
$scope.changePassword = function () {
var resetpassword = {
ID: ID,
NewPassword: $scope.otpnewpassword
};
$http.post(url, resetpassword).then(function (response) {
}, function (error) {
});
}
}]);
})();
This is my html code.
<div class="body-wrapper background-pattern">
<div class="form-wrapper">
<div class="form-container">
<h2 class="form-header">Change Password</h2>
<div class="form-row">
<div class="inputblock">
<span class="input-icon"><img src="images/lock-icon.png"></span>
<input type="password" class="with-icon" placeholder="New Password" ng-model="newpassword">
</div>
<div class="inputblock">
<span class="input-icon"><img src="images/lock-icon.png"></span>
<input type="password" class="with-icon" placeholder="Confirm Password">
</div>
</div>
<div class="button-container">
<input type="button" value="Change Password" id="input-submit" ng-bind="changePassword()">
<input type="submit" value="Cancel" id="input-cancel">
</div>
</div>
</div>
</div>
I am not sure why Ajax call is looping. May I get some help here to fix this? Any help would be appreciated. Thank you.
You are using ng-bind with a function, ngBind attribute tells AngularJS to replace the text content of the specified HTML element Try ng-click instead of that.
<input type="button" value="Change Password" id="input-submit" ng-bind="changePassword()">
to
<input type="button" value="Change Password" id="input-submit" ng-click="changePassword()">

Form Not Clearing after submit POST AngularJS

I'm using angularjs frontend and Play framework backend to process posted data.
The challenge i'm facing is that the form is not resetting after successful posting of data I click submit.
My View is as below and is as below.
<form name="signupForm" ng-submit="signup()" novalidate>
<div>
<label for="email">Email</label>
<input name="email" class="form-control" type="email" id="email" placeholder="Email"
ng-model="email">
</div>
<div>
<label for="password">Password</label>
<input name="password" class="form-control" type="password" id="password"
placeholder="Password" ng-model="password">
</div>
<button type="submit" class="btn btn-primary">Sign up!</button>
</form>
My Angular controller is as below
angular.module('clientApp')
.controller('SignupCtrl', function ($scope, $http, $log) {
$scope.signup = function() {
var payload = {
email : $scope.email,
password : $scope.password
};
$http.post('app/signup', payload)
.success(function(data) {
$log.debug(data);
});
};
});
I'm using chrome browser. How do i get to clear the email and password fields after clicking submit?
Set the $scope.email and $scope.password to null like
$http.post('app/signup', payload)
.success(function(data) {
$log.debug(data);
$scope.email = null;
$scope.password = null;
$scope.signupForm.$setPristine(); //Set form to pristine mode
});

How to submit a form using angular ui bootstrap's modal and csrf

I would like to submit a form using Angular UI Bootstrap's modal. I'm instantiating the modal like:
AdminUsers.factory('ProjectsService', ['$resource', function($resource) {
return $resource('/api/users?sort=createdAt desc');
}]).controller('AdminUsersCtrl', ['ProjectsService', '$scope', '$http', '$modal', '$log', function(ProjectsService, $scope, $http, $modal, $log, $modalInstance) {
$scope.open = function () {
var modalInstance = $modal.open({
templateUrl: '../templates/userModal.html',
controller: function($scope, $modalInstance) {
$scope.user = {};
$scope.ok = function () { $modalInstance.close($scope.user); };
$scope.cancel = function () { $modalInstance.dismiss('cancel'); };
},
resolve: {
items: function () {
return $scope.user;
}
}
});
modalInstance.result.then(function (user) {
$scope.user = user;
$http.post('/api/users/new', $scope.user).success(function() {
$scope.users.unshift($scope.user);
});
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
}
PS: Please note the controller above does have other methods that is not being displayed above.
The code in my userModal.html is:
<div class="modal-header">
<button type="button" class="close" ng-click="cancel()">×</button>
<h6>New customer</h6>
</div>
<div class="modal-body">
<form class="form-horizontal fill-up separate-sections">
<div>
<label>Name</label>
<input type="text" ng-model="user.name" placeholder="Name" />
</div>
<div>
<label>Email</label>
<input type="email" ng-model="user.email" placeholder="Email" />
</div>
<div>
<label>Admin</label>
<select class="form-control" ng-model="user.admin"
ng-options="option as option for option in [true, false]"
ng-init="user.admin=false"></select>
<input type="hidden" name="user.admin" value="{{user.admin}}" />
</div>
<div>
<label>Password</label>
<input type="password" ng-model="user.password" placeholder="Password" />
</div>
<div>
<label>Password confirmation</label>
<input type="password" ng-model="user.confirmation" placeholder="Password confirmation" />
</div>
<div class="divider"><span></span></div>
<div class="divider"><span></span></div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-blue btn-lg" ng-click="ok()">Save</button>
<button class="btn btn-default btn-lg" ng-click="cancel()">Cancel</button>
<input type="hidden" name="_csrf" value=_csrf />
</div>
The problem lies with the hidden input. I need to submit the csrf with form to the server but I don't know how. If this was a jade template I could simply:
input(type="hidden", name="_csrf", value=_csrf)
and Sails/Express would deal with the rest. But because this is a html template used by Angular only, I don't know how to access the _csrf key. I've tried looking into window.document.cookie however it returned undefined.
Can anyone shed some light on this?
Many thanks

AngularJs + php authentication

Hi i started learning AngularJs and now im trying to do my Login module using angular and php, but i have some issues. I have watched alot tutorials but none of them was helpful in my case, so here is what i have: controllers.js:
var controllers = angular.module('controllers', []);
controllers.controller('loginController', ['$scope', '$http', 'UserService', function(scope, $http, User) {
scope.main = [
{username: '', password: ''}
]
scope.login = function(){
var config = {
url: '../auth/login.php',
method: 'POST',
data: {
username: scope.main.username,
password: scope.main.password
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}
$http(config)
.success(function(data,status,headers,config){
if(data.status){
//succefull login
User.isLogged = true;
User.username = data.username;
}
else{
User.isLogged = false;
User.username = '';
}
})
.error(function(data,status,headers,config){
User.isLogged = false;
User.username = '';
});
}
}])
auth.js:
var services = angular.module('services', []);
services.factory('UserService', [function(){
var sdo = {
isLogged: false,
username: ''
};
return sdo;
}]);
login.php:
$username = $_POST['username'];
if($username){
return "Logged";
}else{
return false;
}
and the html:
<div class="col-xs-12" id="loginCol" ng-controller="loginController">
<form ng-submit='login()' name="form" novalidate>
<div class="form-group">
<label for="username" class="sr-only">Username</label>
<input type="text" ng-model="scope.main.username" class="form-control" id="username" placeholder="Име..." />
<label for="password" class="sr-only">Password</label>
<input type="password" ng-model="scope.main.password" class="form-control" id="password" placeholder="Парола..." />
</div>
<div class="form-group pull-right">
<button type="button" class="btn btn-primary">Login</button>
<button type="button" class="btn btn-default">Register</button>
</div>
</form>
</div>
In this case i want just if user type something in the username input and hit the login button and on successful call of login.php to return some message. The problem is that code written like that got error "'loginController' is not a function, got undefined" how to fix it?
(Disclosure: I'm one of the developers of UserApp)
You could try the third-party service UserApp, together with the AngularJS module.
Check out the getting started guide, or take the course on Codecademy. Here's some examples of how it works:
Login form with error handling:
<form ua-login ua-error="error-msg">
<input name="login" placeholder="Username"><br>
<input name="password" placeholder="Password" type="password"><br>
<button type="submit">Log in</button>
<p id="error-msg"></p>
</form>
Signup form with error handling:
<form ua-signup ua-error="error-msg">
<input name="first_name" placeholder="Your name"><br>
<input name="login" ua-is-email placeholder="Email"><br>
<input name="password" placeholder="Password" type="password"><br>
<button type="submit">Create account</button>
<p id="error-msg"></p>
</form>
ua-is-email means that the username is the same as the email.
How to specify which routes that should be public, and which route that is the login form:
$routeProvider.when('/login', {templateUrl: 'partials/login.html', public: true, login: true});
$routeProvider.when('/signup', {templateUrl: 'partials/signup.html', public: true});
The .otherwise() route should be set to where you want your users to be redirected after login. Example:
$routeProvider.otherwise({redirectTo: '/home'});
Log out link:
<a href="#" ua-logout>Log Out</a>
Access user properties:
User info is accessed using the user service, e.g: user.current.email
Or in the template: <span>{{ user.email }}</span>
Hide elements that should only be visible when logged in:
<div ng-show="user.authorized">Welcome {{ user.first_name }}!</div>
Show an element based on permissions:
<div ua-has-permission="admin">You are an admin</div>
And to authenticate to your back-end services, just use user.token() to get the session token and send it with the AJAX request. At the back-end, use the UserApp API with the PHP library to check if the token is valid or not.
If you need any help, just let me know :)
You have created the application
var controllers = angular.module('controllers', []);
but didn't use it in the html code, add ng-app attribute to the wrapper div
<div class="col-xs-12" ng-app="controllers" id="loginCol" ng-controller="loginController">
the second issue, that you try to catch submit event, but don't submit the form, use submit type instead button
<button type="submit" class="btn btn-primary">Login</button>
or add ng-click="login()" attribute to the button and remove ng-submit='login()' from the form

Categories