I'm trying to create a user registration with Angular, that creates a user in my Django backend. When I press the Signup button nothing happens.
This is my first time working with Angular, so I understand my syntax and logic might be completely off. But I feel like if I can learn this part, It will set me up for doing the other things I need to do with Angular.
To save myself some time I'm trying to appropriate Tivix's angular-django-auth from github into my own project, so my controller really is just the Tivix one, that I tried to shove into my own project, but I can't seem to make it work. I'm sorry if this question is stupid, but I'm still trying to learn Angular, and how all the pieces are supposed to work together.
Note: my API Server is running on localhost:8000 and Ionic is running on localhost:4400, so I don't know if that might be a problem too?
Here's my controller:
.controller('signupCtrl', ['$scope', '$stateParams', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams, djangoAuth, Validate) {
$scope.model = { 'username': '', 'password': '', 'email': '' };
$scope.complete = false;
$scope.register = function (formData) {
$scope.errors = [];
Validate.form_validation(formData, $scope.errors);
if (!formData.$invalid) {
djangoAuth.register($scope.model.username, $scope.model.password1, $scope.model.password2, $scope.model.email)
.then(function (data) {
// success case
$scope.complete = true;
}, function (data) {
// error case
$scope.errors = data;
});
}
}
}])
<ion-view title="Signup" hide-nav-bar="true" id="page2" style="background-color:#F1F1F1;">
<ion-content padding="true" class="manual-ios-statusbar-padding">
<div class="spacer" style="width: 300px; height: 18px;"></div>
<div>
<img src="img/aSVlyHt1SqywcHmw4wIg_logo.svg" width="80%" height="auto" style="display: block; margin-left: auto; margin-right: auto;">
</div>
<div class="spacer" style="width: 300px; height: 59px;"></div>
<div ng-controller="signupCtrl">
<form id="signup-form1" ng-if="authenticated != true" ng-submit="register(registerForm)" novalidate class="list">
<ion-list id="signup-list1">
<label class="item item-input" id="signup-input1">
<span class="input-label">Email:</span>
<input type="email" ng-model="model.email" placeholder="">
</label>
<label class="item item-input" id="signup-input2">
<span class="input-label">Username:</span>
<input type="text" ng-model="model.username" placeholder="">
</label>
<label class="item item-input" id="signup-input3">
<span class="input-label">Password:</span>
<input type="password" ng-model="model.password1" placeholder="">
</label>
</ion-list>
<button id="signup-button12" style="left:-10px;" type="submit" class="button button-energized button-full">Sign Up</button>
</form>
</div>
<!-- <div style="margin-right:-20px;">
<button id="signup-button12" style="left:-10px;" type="submit" class="button button-energized button-full">Sign Up</button>
</div>-->
<a ui-sref="login" id="signup-button6" class="button button-positive button-block button-clear">Or login</a>
</ion-content>
</ion-view>
Related
I have created a new project, but got a problem which I am not able to fix.
Here's my example:
I have this error :
"Error: [$controller:ctrlreg] The controller with the name 'PostController' is not registered."
Connexion.html
<section id="login" ng-controller="PostController as postCtrl">
<div class="container center-bloc">
<div class="row">
<div class="col-xs-12">
<div class="form-wrap">
<div class="text-center">
<img id="logo" style="max-width:100%;" src="img.png">
</div>
<h2 id="ResultConnexion"></h2>
<form role="form" id="login-form" ng-submit="postCtrl.Search1()" method="POST" autocomplete="off">
<div class="form-group">
<input id="userLogin" required autofocus ng-model="postCtrl.inputData.username" type="text" name="user" id="email" class="form-control" placeholder="exemple#example.com">
</div>
<div class="form-group">
<input id="userPassword" required ng-model="postCtrl.inputData.password" type="password" name="mdp" id="key" class="form-control" placeholder="Password">
</div>
<button type="submit" class="btn btn-custom btn-lg btn-block" ng-disabled="login.$invalid" >Connexion</button>
<div class="alert alert-danger" ng-show="errorMsg">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">
×</button>
<span class="glyphicon glyphicon-hand-right"></span> {{errorMsg}}
</div>
<div></div>
</form>
<hr>
</div>
</div>
</div>
</div>
index. js
'use strict';
var routeApp = angular.module("routeApp", ["ngRoute"]);
routeApp.config(function($routeProvider) {
$routeProvider
.when("/", {
url: "/",
templateUrl : "template/connexion.html",
controller : "PostController"
})
});
var routeAppControllers = angular.module('routeAppControllers',['ngRoute']);
routeAppControllers.controller('PostController', ['$scope', '$http', function($scope, $http) {
this.postForm = function() {
var Pass = {"user":(this.inputData.username),"mdp":(this.inputData.Password)};
$http({
method: 'POST',
url: '/',
data: Pass,
headers: {'Content-Type': 'application/json'}
})
.then(function(response) {
if ( response.data.resultat == 0) {
window.location.href = '/information';
alert('hello')
} else {
$scope.errorMsg = 'Bad';
}
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
})
}
}]);
Can anybody help?
You have two separate modules showing and neither is injected in the other.
Assuming your ng-app uses routeApp you need to inject routeAppControllers module into routeApp module
var routeApp = angular.module("routeApp", ["ngRoute", "routeAppControllers"]);
Also you only need to inject ngRoute once.
As noted in other answer you only use ng-controller when it is not declared in routing config also, or you end up with multiple controller instances
I think you should remove ng-controller="PostController as postCtrl"> from template .Because you defined it in route . and also change to below.
.when("/", {
url: "/",
templateUrl : "template/connexion.html",
controller : "PostController as postCtrl"
})
another tip that recommended you declare var vm = this and use vm instead of this
vm.postForm = function() {...}
I have a form, when I submit it, it pushes some object to my array. Beneath that form I have a table that shows all items in that array. I want my table to update automatically (without refreshing the page) when new item pushed.
Submit button:
<button type="submit" class="btn btn-default" ng-click="updateTable()">Pay</button>
In my controller:
$scope.updateTable = function() {
setTimeout(function () {
$scope.$apply();
$scope.$digest();
}, 0);
};
However, it does not work.
I tried different approaches like $watch service, but i`ve got the same result.
Table
<div class="row paytable">
<div class="col-xs-10 col-xs-offset-1">
{{payments.length}}
<table class="table table-hover ">
<tr>
<td>Id</td>
<td>Amount</td>
<td>Cause</td>
</tr>
<tr ng-repeat="item in payments">
<td>{{item.id}}</td>
<td>{{item.amount}}</td>
<td>{{item.cause}}</td>
</tr>
</table>
</div>
</div>
Controller
app.controller('mainController', [ 'user', '$rootScope', '$scope', 'payment', '$timeout', function(user, $rootScope, $scope, payment, $timeout) {
user.getUsers();
user.newUser();
$rootScope.currentUser = user.currentUser();
$scope.payments = payment.getPayments();
$scope.newPayment = payment.newPayment;
$scope.updateTable = function() {
setTimeout(function () {
console.log('apply ------------');
$scope.$apply();
$scope.$digest();
}, 0);
};
$scope.showPayMessage = function() {
console.log('im here');
$scope.showSM = true;
$timeout(function() {
$scope.showSM = false;
}, 2000);
};
}]);
payment - my service for array manipulation.
Form
<div class="newpay row" >
<div class=" col-xs-10 col-xs-offset-1">
<h1>Hello, {{currentUser.name}}</h1>
<h4 ng-show="showSM" class="bg-success">Payment confirmed</h4>
<form name="inputform" ng-submit="newPayment(amount, cause); showPayMessage();">
<div class="form-group">
<label for="exampleInputEmail1">Amount</label>
<input type="number" name="amount" ng-model="amount" class="form-control" id="exampleInputEmail1" placeholder="Amount" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Cause</label>
<input type="text" name="cause" ng-model="cause" class="form-control" id="exampleInputPassword1" placeholder="Cause" required>
</div>
<button type="submit" class="btn btn-default" ng-click="updateTable()">Pay</button>
</form>
</div>
</div>
payments: {{payments.length}}
<payments-table payments="payments"></payments-table>
To display that table I created directive.
$scope.$apply and $scope.$digest are better suited for working with 3rd party libraries or testing. In your case Angular is well aware to your changes. The thing is, your payments array, that resides in a service should be queried again after submitting a new item (unless you have a direct reference to the array, then no query should be made).
Like this:
View
<form name="inputform" ng-submit="onSubmit()">
Controller
$scope.onSubmit = function() {
newPayment($scope.newItemAmount, $scope.newItemCause); // Assuming they are properties in the controller
showPayMessage();
$scope.payments = payment.getPayments(); // getting the updated array
}
I'm trying to make a little app in ionic, but it gave me that error when i call the $scope.saveClass() function from the UI.
Unable to get property 'subject' of undefined or null reference
I don't understand because he doesn't work. Premise: i'm new to ionic/angularjs developing.
I thank you in advance for helping
code (www/js/controllers.js)
angular.module('starter.controllers')
.service("DB", function() {
this.classDB = new PouchDB("classesDB");
})
.controller("AddClassCtrl", function ($scope, DB) {
$scope.saveClass = function () {
var newclass = {
"_id": $scope.class.subject,
"subject": $scope.class.subject,
"room": $scope.class.room
}
DB.classDB.put(newclass);
window.location.href = '#app/schedule'
};
})
Code (add-class.html)
<ion-content controller="AddClassCrtl">
<div class="list">
<!--Select the subject-->
<label class="item item-input item-select">
<div class="input-label">
Subject
</div>
<button class="button button-block button-positive overflowShow"> Add a subjects </button>
<select class="item-input" ng-model="class.subject" ng-selected="class.subject">
<option ng-repeat="subject in subjects">{{subject}}</option>
</select>
</label>
<!--Insert the room number-->
<label class="item item-input item-stacked-label">
<input type="text" placeholder="Room" ng-model="class.room" ng-text-change="class.room">
</label>
<div class="item">
<button ng-click="discardClass()" class="button button-block">Discard</button>
<button ng-click="saveClass()" class="button button-block">Save</button>
</div>
</div>
</ion-content>
It's probably because you didn't initialize $scope.class variable and in fact, when you try to access $scope.class.subject, $scope.class is undefined. Add this code at the beginning of your controller:
$scope.class = {};
I have the following controller:
app.controller('SignUpController', ['$http','$sessionStorage','api', '$scope','$state', '$log', 'Session','clientSocket', function ($http, $sessionStorage, api, $scope,$state, $log, Session, clientSocket) {
var signupCtrl = this;
signupCtrl.getRandomPerson = function () {
var isGuy = Math.floor((Math.random() * 2));
if(isGuy == 1 || isGuy == 0){
var picture = Math.floor((Math.random()*9));
return 'img/guys/guy-'+picture+'.jpg';
}else{
var picture = Math.floor((Math.random()*10));
return 'img/guys/woman-'+picture+'.jpg';
}
}
}]);
With the following html:
<div class="container w-xxl w-auto-xs" ng-controller="SignUpController as signUpCtrl" ng-init="app.settings.container = false;">
<div class="m-b-lg">
<div class="bg-white p-md">
<div class="block m-t text-center m-b-xl">
<img src="{{signUpCtrl.getRandomPerson()}}" alt="Company Logo" class="img-circle" style="display: inline-block">
</div>
<form name="form" class="form-validation">
<div class="list-group list-group-sm">
<div class="list-group-item">
<input placeholder="Name" class="form-control no-border" ng-model="user.name" required>
</div>
<div class="list-group-item">
<input type="email" placeholder="Email" class="form-control no-border" ng-model="user.email" required>
</div>
<div class="list-group-item">
<input type="password" placeholder="Password" class="form-control no-border" ng-model="user.password" required>
</div>
</div>
<div class="checkbox m-b-md m-t-none">
<label class="i-checks">
<input type="checkbox" ng-model="agree" required><i></i> Agree the <a href>terms and policy</a>
</label>
</div>
<button type="submit" class="btn btn-lg btn-primary btn-block" ng-click="signup()" ng-disabled='form.$invalid'>Sign up</button>
<div class="line line-dashed"></div>
<p class="text-center"><small>Already have an account?</small></p>
<a ui-sref="access.signin" class="btn btn-lg btn-default btn-block">Sign in</a>
</form>
</div>
</div>
<div class="text-center" ng-include="'tpl/blocks/page_footer.html'">
{% include 'blocks/page_footer.html' %}
</div>
When i am loading this page the function getRandomPerson gets fired over 10 times. Sometimes so much that angular throws the following execption:
Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [[{"msg":"fn: expressionInputWatch","newVal":"img/guys/guy-2.jpg","oldVal":"img/guys/guy-1.jpg"}],[{"msg":"fn: expressionInputWatch","newVal":"img/guys/guy-6.jpg","oldVal":"img/guys/guy-2.jpg"}],[{"msg":"fn: expressionInputWatch","newVal":"img/guys/guy-1.jpg","oldVal":"img/guys/guy-6.jpg"}],[{"msg":"fn: expressionInputWatch","newVal":"img/guys/guy-4.jpg","oldVal":"img/guys/guy-1.jpg"}],[{"msg":"fn: expressionInputWatch","newVal":"img/guys/guy-8.jpg","oldVal":"img/guys/guy-4.jpg"}]]
http://errors.angularjs.org/1.3.14/$rootScope/infdig?p0=10&p1=%5B%5B%7B%22m…guys%2Fguy-8.jpg%22%2C%22oldVal%22%3A%22img%2Fguys%2Fguy-4.jpg%22%7D%5D%5D
at REGEX_STRING_REGEXP (angular.js:63)
at Scope.$get.Scope.$digest (angular.js:14281)
at Scope.$get.Scope.$apply (angular.js:14506)
at done (angular.js:9659)
at completeRequest (angular.js:9849)
at XMLHttpRequest.requestLoaded (angular.js:9790)
Can anyone tell me whats going on?
The issue is that many digests might run on a particular scope within the page...even just to render once
Because every digest is seeing a new value from your function, it forces another digest. Thus you are creating an infinte loop
Just assign a scope variable randomImage and get that value returned from function, instead of placing function in the html
And as pointed out use ng-src so that final src gets set with a proper value after it is compiled. Otherwise you will have strange invalid path requests made to server
// will only run once when controller initializes
signupCtrl.randomImage = getRandomPerson();
// no need to be on scope since using it privately
var getRandomPerson = function() {
var isGuy = Math.floor((Math.random() * 2));
if(isGuy == 1 || isGuy == 0){
var picture = Math.floor((Math.random()*9));
return 'img/guys/guy-'+picture+'.jpg';
}else{
var picture = Math.floor((Math.random()*10));
return 'img/guys/woman-'+picture+'.jpg';
}
}
HTML
<!-- No src so browser won't make request to invalid path -->
<img ng-src="{{signUpCtrl.randomImage }}">
You have a src binding to your function, if you intend to do this you should be using ng-src so it won't be compiled before it is ready to be consumed.
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