Error: [ng:areq] Argument 'AuthCtrl' is not a function, got undefined - javascript

This issue has been posted a few times but I cannot seem to find the error within my code. Can somebody help spot the issue in my code?
Below is my app.js file
'use strict';
/**
*jslint node:true
* #ngdoc overview
* #name impApp
* #description
* # impApp
*
* Main module of the application.
*/
/*global Firebase, angular*/
angular
.module('impApp', [
'ngMessages',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'firebase'
])
.config(function ($routeProvider) {
$routeProvider
.when('/main', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
controllerAs: 'main'
})
.when('/', {
templateUrl: 'views/login.html',
controller: 'AuthCtrl',
controllerAs: 'auth'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl',
controllerAs: 'about'
})
.otherwise({
redirectTo: '/'
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
Secondly, this is my controller contents on "auth.js":
'use strict';
/*global Firebase, angular, console*/
angular.module('impApp')
// Re-usable factory that generates the $firebaseAuth instance
.factory("Auth", function ($firebaseAuth) {
var ref = new Firebase("https://impl.firebaseio.com");
return $firebaseAuth(ref);
})
.controller('AuthCtrl', function ($scope, $http, Auth) {
// Listens for changes in authentication state
Auth.$onAuth(function (authData) {
$scope.authData = authData;
});
// Logs in a user with email & password
$scope.login = function () {
Auth.authWithPassword({
email : $scope.email,
password : $scope.password
}, function (error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
});
};
// Logs out the logged-in user
$scope.logout = function () {
Auth.$unauth();
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
Finally, I have outlined the "login.html" contents:
<div>
<form class="form-signin">
<h2 class="form-signin-heading">Please Sign In</h2>
<input type="text" class="form-control" name="username" ng-model = "username" placeholder="Email Address" required="" autofocus="" />
<input type="password" class="form-control" name="password" ng-model = "password" placeholder="Password" required=""/>
<p></p>
<button class="btn btn-lg btn-primary btn-block" type="submit" ng-click="login()">Login</button>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

Thank you Pierre-Alexandre. Adding the link to the js file in the index.html resolved this issue.

Related

Shows entire html page instead of showing 404 error in Angularjs

login.html
Username: <input type="text" ng-model="user.username"><br/>
Password: <input type="text" ng-model="user.password"> <br/>
<input type="button" value="Login" ng-click="login(user)">
login.js
app.controller('loginCtrl', function($scope, $http){
$scope.login = function(user){
console.log(user);
$http.post('/login', user)
.success(function(response){
console.log(response);
});
};
});
For first console.log(user) it shows username and password on console but after i do console.log(response) it shows entire index.html page instead of showing 404 error, since there is no mapping for /login in the node server.
app.js
var app = angular.module('myApp', ['ngRoute']);
app.config(['$routeProvider','$locationProvider',function($routeProvider, $locationProvider){
$routeProvider
.when('/home',{
templateUrl: 'views/home.html'
})
.when('/login',{
templateUrl: 'views/login/login.html',
controller: 'loginCtrl'
})
.otherwise({
redirectTo: '/home'
});
$locationProvider.html5Mode(true);
}]);

$on don't catch $broadcast

I have a Angular Project and I want create Authentication mechanism so i have the following controller:
angular.module('authModule')
.controller('LoginCtrl', function($rootScope, $location, loginRESTService, UserService){
var login = this;
function signIn(user) {
loginRESTService.login(user)
.then(function(response) {
console.log(response);
user.access_token = response.user_id;
UserService.setCurrentUser(user);
$rootScope.$broadcast('authorized');
$location.path("/formList");
});
}
})
additional I have a main controller with the following methods
angular.module('authModule')
.controller('MainCtrl', function ($rootScope, $state, LoginService, UserService) {
var main = this;
$rootScope.$on('authorized', function() {
console.log("ENTRE CON PERMISO");
main.currentUser = UserService.getCurrentUser();
});
$rootScope.$on('unauthorized', function() {
console.log("ENTRE SIN PERMISO");
main.currentUser = UserService.setCurrentUser(null);
$state.go('login');
});
})
the problem it's that 'authorized' and 'unauthorized' never was invoked and don't have idea why
my app.js file
angular
.module('pysFormWebApp', [
...
'translateModule',
'formModule',
'authModule'
])
.config(function ($routeProvider, $httpProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
controllerAs: 'main'
})
.when('/login', {
templateUrl: 'views/auth/login.html',
controller: 'LoginCtrl',
controllerAs: 'login'
})
.otherwise({
redirectTo: '/'
});
my index.html (only a part because is so long and is the index that generate yo angular)
<div ng-controller="MainCtrl as main" >
<button ng-if="main.currentUser" class="btn btn-default navbar-btn" ng-click="main.logout()">Logout <strong>{{main.currentUser.name}}</strong>
</button>
</div>
First, you are not broadcasting the 'unauthorized' event. because of that the $rootScope.on('unauthorized') is not working.
Second. Maybe are running the main controller before the login controller, and because of that your controller doesn't catch the event.
let me know if it solves your problem.

Angular login/authentication against restful API

I have created a basic authentication system in an angular app which is written against hardcoded credentials - see below:
app.js
/* global app:true */
/* exported app */
'use strict';
/**
* #ngdoc overview
* #name WebAppApp
* #description
* # WebAppApp
*
* Main module of the application.
*/
var app = angular
.module('WebAppApp', [
'ngAnimate',
'ngAria',
'ngCookies',
'ngMessages',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/login.html',
controller: 'loginCtrl',
controllerAs: 'login'
})
.when('/home', {
templateUrl: 'views/home.html'
//controller: 'loginCtrl',
//controllerAs: 'login'
})
.otherwise({
redirectTo: '/'
});
});
login.html
<form ng-submit="submit()">
Username: <input type="text" id="username" ng-model="username" /><br>
Password: <input type="password" id="password" ng-model="password" /><br>
<input type="submit" value="Submit" />
</form>
login.js
'use strict';
//app global variable
//this is hte controller that handles post requests
app.controller('loginCtrl', function ($scope, $location) {
$scope.submit = function(){
var uname = $scope.username;
var password = $scope.password;
if($scope.username == 'admin' && $scope.password == 'admin'){
$location.path('/home');
} else {
alert('username or password is wrong');
}
};
});
This works. What I want to do now, is check the username and password against an api call by posting the data to the server /login, if successful an access token is returned, and is then stored inside of a cookie. At which point the user gets access to the rest of the application.
If the credentials fails, for validation takes place preventing the user from logging in.
What is the best way to do this?
First of all check this url
Your code would look something like this:
$scope.submit = function(){
$http.post('/login', {
username:$scope.username,
password:$scope.password
}).then(function(response) {
if (response.data=="ok") {
//Login was ok
$location.path("/home");
} else {
//Login was not ok
}
}, function(response) {
//Error happend, response.status or response.statusText have details
});
}

$state.go not working - Error : $state isnot defined

Hi im Very new Angulay js Ionic development. im trying to basic navigation when button is clicked. but im getting this error when i click the button in Firebug console . i want to navigate to the search page after it clicked
Error : $state isnot defined
Here my App.js Code
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('signin', {
url: "/sign-in",
templateUrl: "templates/sign-in.html",
controller: 'AppCtrl'
})
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
})
.state('app.search', {
url: "/search",
views: {
'menuContent': {
templateUrl: "templates/search.html"
}
}
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/sign-in');
});
here my Controller
angular.module('starter.controllers', [])
.controller('AppCtrl', function($scope, $ionicPopup, $timeout, $ionicModal) {
$scope.signIn = function(user) {
//console.log('Sign-In', user);
$state.go('app.search');
};
})
My HTML button is
<button class="button button-block button-positive" id="login-btn" ng-click="signIn(user)" type="submit">Log in</button>
You should also get in the habit of properly injecting your dependencies. It should look like this (including the $state injection):
.controller('AppCtrl',['$scope', '$ionicPopup', '$timeout', '$ionicModal', '$state', function($scope, $ionicPopup, $timeout, $ionicModal, $state) {
$scope.signIn = function(user) {
//console.log('Sign-In', user);
$state.go('app.search');
};
}])
Just make sure the order of injections in the quotes are in the same order as the order of your parameters in the following function.

How can I get ui-keypress working in my Angular JS app?

My app has a login form consisting of a username, password, and a button to click to log in. However, for some reason I just can't get ui-keypress to work on the login button. I'm using ui-bootstrap and ui-utils. ui-utils has the keypress directive included.
Here's what I have so far:
My login partial:
<div id="loginForm">
<img id="logo" src="img/login_logo.png"/>
<alert ng-repeat="alert in alerts" type="alert.type" close="closeAlert($index)">
{{alert.msg}}
</alert>
<input type="text" id="username" ng-model="username" placeholder="Username"/>
<input type="password" id="password" ng-model="password" placeholder="Password"/>
<button type="button" id="loginBtn" class="btn btn-primary" ng-model="loginModel" ng-click="login()" ui-keypress="{13:'keypressLogin($event)'}">
Login
</button>
</div>
My login controller:
ClutchControllers.controller("LoginController", [
'$scope',
'$http',
'$location',
'$cookieStore',
'Auth',
function($scope, $http, $location, $cookieStore, Auth) {
// Redirect if already logged in
if(Auth.isLoggedIn()) {
$location.path('/dashboard');
}
$scope.alerts = [];
$scope.closeAlert = function(index) {
$scope.alerts.splice(index, 1);
}
$scope.login = function() {
Auth.login({
username: $scope.username,
password: $scope.password
}, function(err, user) {
if(err) {
console.log(err);
$scope.alerts = [err];
} else {
console.log(user);
console.log(Auth.isLoggedIn());
//this this if you want to change the URL and add it to the history stack
$location.path('/dashboard');
}
});
}
$scope.keypressLogin = function($event) {
console.log($event);
console.log($scope.username);
}
}
]);
And finally, my app routing:
angular.module('myApp', [
'ngCookies',
'ui.utils',
'ui.bootstrap',
'ui.utils',
'clutch.services',
'clutch.controllers'
])
.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider) {
$routeProvider
.when('/login', {
controller: "LoginController",
templateUrl: "partials/login.html",
auth: false
})
.when('/dashboard', {
controller: "DashboardController",
templateUrl: "partials/dashboard.html",
auth: true
})
.otherwise({ redirect: "/login" });
}]);
ClutchControllers = angular.module('clutch.controllers', ['ui.bootstrap']);
ClutchServices = angular.module('clutch.services', ['ngResource']);
Just a thought, why would you want to use ui-keypress. IMHO using a form is better solution in this case. Consider this...
<form ng-submit="login()">
<input type="text"/>
<input type="password"/>
<button type="submit">Login</button>
</form>
Taking a wild guess -- you've got the ui-keypress attribute on your button and not your two input tags..
Took me a bit to reproduce in jsfiddle w/ all your dependencies: http://jsfiddle.net/tuv45/

Categories

Resources