Angular Routing is not working after logging in - angularjs

I am trying to login using username and password and displaying a home page.
Homepage contains hyperlink, clicking that should direct to someother content which is not happening.
Can someone help me in this regard.
var app = angular.module('plunker', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider.
when('/login', {
templateUrl: 'pages/login.html',
controller: 'AppCtrl'
}).
when('/home',{
templateUrl: 'pages/country-list.html',
controller:'CountryListCtrl'
}).
when('/:countryName',{
templateUrl: 'pages/country-detail.html',
controller:'CountryDetailCtrl'
}).
otherwise({
redirectTo: '/login'
});
});
app.run(['$rootScope', '$location', 'Auth', function ($rootScope, $location, Auth) {
$rootScope.$on('$routeChangeStart', function (event) {
console.log('Auth logged:'+Auth.isLoggedIn());
if (!Auth.isLoggedIn()) {
console.log('DENY');
event.preventDefault();
$location.path('/login');
}
else {
console.log('ALLOW');
$location.path('/home');
}
});
}]);
app.factory('Auth', function(){
var user;
console.log('user'+user);
return{
setUser : function(aUser){
user = aUser;
},
isLoggedIn : function(){
return(user)? user : false;
}
}
});
app.controller('AppCtrl', ['$rootScope','$scope','$location', 'Auth',function($rootScope,$scope,$location, Auth) {
$scope.$watch(Auth.isLoggedIn, function (value, oldValue) {
console.log('value'+value);
console.log('not value'+!value);
console.log('oldValue'+oldValue);
if(!value && oldValue) {
console.log("Disconnect");
$location.path('/login');
}
if(value) {
console.log("Connect");
//Do something when the user is connected
}
}, true);
$rootScope.user = {};
$scope.login = function (username, password) {
if ( username === 'admin' && password === '1234') {
$rootScope.user.name= username;
$rootScope.user.password= password;
Auth.setUser($scope.user);
$location.path( '/home' );
} else {
$scope.loginError = "Invalid username/password combination";
};
};
}]);
app.controller('CountryListCtrl', function ($scope, $http){
$http.get('json/countries.json').success(function(data) {
$scope.countries = data;
});
});
app.controller('CountryDetailCtrl', function ($scope, $routeParams,$location){
console.log('countrName route'+$routeParams.countryName);
$scope.name = $routeParams.countryName;
console.log('countrName $scope.name'+$scope.name);
});
index.html
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="css/style.css" />
<script src="js/angular.min.js"></script>
<script src="js/angular-route.min.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-controller="AppCtrl">
<div ng-view></div>
</body>
</html>
Login.html
<h1>Login Page</h1>
<form ng-submit="login(username, password)" class="ng-scope ng-pristine ng-valid">
<label>User name</label>
<input type="text" ng-model="username" class="ng-pristine ng-valid">
<label>Password</label>
<input type="password" ng-model="password" class="ng-pristine ng-valid">
<br/>
{{loginError}} {{loggedUser}}
<br/><br/>
<button class="btn btn-success" ng-click="">Submit</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</form>
country-list.html
<h1>Country List</h1>
<div>Welcome :<strong>{{user.name}}</strong></div>
<span class="logout">Logout</span>
<ul>
<li ng-repeat="country in countries">{{country.name}}</li>
</ul>
country-detail.html
<h1>Country Detail</h1>
<h1>{{name}}</h1>
Problem is with CountryDetailCtrl I guess. but cosnole values are coming fine.
Can someone let me know where I am going wrong.

no need in $rootScope here just use one call of
if (!Auth.isLoggedIn()) {
console.log('DENY');
$location.path('/login');
return; // not to execute your controller function further
}
on start of each of you view controllers, that should be protected, "return" will stop execution of controller code written bellow.

Related

why ng-view doesn't display anything in my angularjs code

I'm new to AngularJS and I tried creating a sample login page and I tried routing to other page on successful login but nothing shows up in ng-view and my code has no error. What could be the problem?
index.html
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-
route.js"></script>
<script src="maincontroller.js"></script>
</head>
<body>
<div ng-view>
</div>
</body>
</html>
controller
var app = angular.module('myapp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'login.html',
controller: 'maincontroller'
})
.when('/dashboard', {
templateUrl: 'dashboard.html'
})
.otherwise('/', {
templateUrl: '/'
})
});
app.controller('maincontroller', function($scope, $location) {
$scope.submit = function($scope) {
var username = $scope.username;
var password = $scope.password;
if ($scope.username == 'ashok' && $scope.password == 'ashok') {
$location.path('/dashboard');
} else {
windows.alert('wrong stuff');
}
};
});
login.html
<div ng-controller="maincontrol">
<form action="/" name="formgroup">
<label>Username:<input type="text" id="username" ng-model="username"/></label><br>
<label>Password:<input type="password" id="password" ng-model="password"/></label><br>
<button type="button" ng-click="submit()">Login</button>
</form>
You should mention ng-app in your HTML to make this an Angular app.
<html ng-app='myapp'>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-
route.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-view>
</div>
</body>
</html>
Maincontroller.js
var app = angular.module('myapp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'login.html',
controller: 'maincontroller'
})
.when('/dashboard', {
templateUrl: 'dashboard.html'
})
.otherwise('/', {
templateUrl: '/'
})
});
app.controller('maincontroller', function($scope, $location) {
$scope.submit = function() {
var username = $scope.username;
var password = $scope.password;
if ($scope.username == 'ashok' && $scope.password == 'ashok') {
$location.path('/dashboard');
} else {
windows.alert('wrong stuff');
}
};
});
$scope is already injected in to the controller and you are passing that as a parameter to your submit function which is undefined since you did not pass anything on submit.
Login.html
<form action="/" name="formgroup">
<label>Username:<input type="text" id="username" ng-model="username"/></label><br>
<label>Password:<input type="password" id="password" ng-model="password"/></label><br>
<button type="button" ng-click="submit()">Login</button>
</form>
Since you are injecting controller on routing, You don't have to use ng-controller in your login.html. It makes the controller execute again.
Check this Plunker: https://plnkr.co/edit/8jPJ7WOa3ixjqeRU8bpg?p=preview
I will recomment to use ng-app in body .
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-
route.js"></script>
<script src="maincontroller.js"></script>
</head>
<body ng-app="myapp">
<div ng-view>
</div>
</body>
</html>
also User maincontroller in login page
<div ng-controller="maincontroller">
<form action="/" name="formgroup">
<label>Username:<input type="text" id="username" ng-model="username"/></label><br>
<label>Password:<input type="password" id="password" ng-model="password"/></label><br>
<button type="button" ng-click="submit()">Login</button>
</form>
</div>

Angularjs. Error: $controller:ctrlreg A controller with this name is not registered

I'm getting the following error on the chrome console:
The controller with the name 'registerCtrl' is not registered.
for some reason, my registerCtrl is not being recognized when routing to the root or /register.
for some reason, my registerCtrl is not being recognized when routing to the root or /register.
Index.html
<html ng-app="testApp">
<head>
<base href="/">
<title></title>
<link href="Content/bootstrap.css" rel="stylesheet" />
<script src="Scripts/jquery-3.2.1.min.js"></script>
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/angular-route.min.js"></script>
<script src="app/app.js"></script>
<script src="app/register/registerCtrl.js"></script>
<script src="app/adminDashBoard/adminDashBoardCtrl.js"></script>
<script src="app/services/hubProxy.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
<script src="app/directives/alerts/alertDir.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
app.js(boostrap)
(function () {
var app = angular.module('testApp', ["ngRoute"]);
app.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when("/", {
templateUrl: "/app/register/register.html",
controller: 'registerCtrl'
})
.when("/register", {
templateUrl: "/app/register/register.html",
controller: 'registerCtrl'
})
.when("/adminDashBoard", {
templateUrl: "/app/adminDashBoard/adminDashBoard.html",
controller:'adminDashboardCtrl'
})
});
})();
registerCtrl
(function () {
var registerController = function ($scope, hubProxy) {
var hub = hubProxy("", "UserRegisterHub");
$scope.registerUser = function () {
// call hub and pass these details
if ($scope.userName !== "" && $scope.emailAddress !== "") {
hub.invoke("RegisterUser", function (result) {
// confirm user use boostrap alert
$scope.showAlert = true;
});
}
}
$scope.userName = "yoyoy";
$scope.email = "";
};
angular.module("testApp").controller('RegisterCtrl', registerController);
})();
register.Html
<div>
<a ng-href="adminDashBoard">Admin Dashboard</a>
<alert showAlert="true"></alert>
<label>{{userName}}</label>
<form name="register">
<div>
<label>Name</label>
<input type="text" required="" ng-model="userName" />
</div>
<div>
<label>Email</label>
<input type="text" required="" ng-model="email" />
</div>
<div>
<input type="submit" ng-click="registerUser()" value="submit" />
</div>
</form>
</div>
Any ideas? thanks

Login is not working unless I remove the "." from ".config"

I am having trouble with my app. When my app.js is the same as below I get an error alert with undefined but if I remove the "." and leave it as config the login function works fine and returns a response. What am I doing wrong?
app.js
angular.module('app',['angular-jwt','angular-storage', 'ngRoute', 'ui.router'])
.config(function ($stateProvider, $urlRouterProvider, jwtInterceptorProvider, $httpProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state("login", {
url:"/login",
controller: "loginController",
templateUrl: "login.html"
})
.state("signup", {
url:"/signup",
controller: "/Controllers/signupController",
templateUrl: "register.html"
});
jwtInterceptorProvider.tokenGetter = function (store) {
return store.get('jwt');
};
$httpProvider.interceptors.push('jwtInterceptor');
})
.run(function($rootScope, $state, store, jwtHelper) {
$rootScope.$on('$stateChangeStart', function(e, to) {
if (to.data && to.data.requiresLogin) {
if (!store.get('jwt') || jwtHelper.isTokenExpired(store.get('jwt'))) {
e.preventDefault();
$state.go('login');
}
}
});
});
loginController.js
'use strict';
angular.module('app')
.controller('loginController', function ($scope, $http, $state, store) {
$scope.user = {};
$scope.login = function() {
$http({
url: '',
method: 'POST',
data: $scope.user
}).then(function(response) {
console.log("res", response.data.token);
store.set('jwt', response.data.token);
var test1 = store.get('jwt');
console.log("get", test1);
//$state.go('login');
}, function(error) {
console.log();
alert(error.data);
});
}
});
login.html
<body class="main" ng-app="app" ng-controller="loginController">
<div class="form" data-ix="new-interaction-2">
<label class="field-label" for="Name-2">Email</label>
<input class="text-field-2 w-input" data-name="name" id="Name-2" maxlength="256" name="name" placeholder="Email" required="required" type="email" ng-model="user.email">
<label for="Password-2">Password:</label>
<input class="text-field w-input" data-name="Password" id="Password-2" maxlength="256" name="Password" placeholder="Password" required="required" type="password" ng-model="user.password">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-messages/1.6.4/angular-messages.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-storage/0.0.15/angular-storage.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-route.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-resource.js" type="text/javascript"></script>
<script src="/app.js"></script>
<script src="/node_modules/angular-jwt/dist/angular-jwt.js"></script>
<script src="/Controllers/loginController.js"></script>
<script src="/Controllers/testController.js"></script>
My file structure
Fixed it. Had to whitelist my domain in app.js by adding
jwtOptionsProvider.config({
whiteListedDomains: ['api.api', 'localhost']
});

AngularJS Route with Spring Security

I was following a Spring Security/AngularJS tutorial to learn the mechanics of it. I was pretty confident that I had the business logic in place to route from a CSS login page to a CSS-based dashboard page. Here is my index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../img/favicon.ico">
<title>Sample App</title>
<!-- Bootstrap core CSS -->
<link href="../css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="../css/signin.css" rel="stylesheet">
</head>
<body ng-app="hello">
<div ng-controller="loginController as controller" class="container">
<form role="form" class="form-signin" ng-submit="controller.login()">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputUsername" class="sr-only">Username</label>
<input type="text" id="username" name="username" ng-model="controller.credentials.username"
class="form-control" placeholder="Username" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="password" name="password" ng-model="controller.credentials.password"
class="form-control" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div> <!-- /container -->
<script src="js/angular-bootstrap.js" type="text/javascript"></script>
<script src="../js/sample.js"></script>
</body>
</html>
Here is the sample.js file:
angular.module('hello', [ 'ngRoute' ]).config(
function($routeProvider, $httpProvider) {$routeProvider
.when('/', {
templateUrl : 'index.html',
controller : 'loginController',
controllerAs: 'controller'
})
.when('/dashboard', {
templateUrl : 'dashboard.html',
controller : 'dashboardController',
controllerAs: 'controller'
})
.otherwise('/');
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
}).controller('loginController', function($rootScope, $http, $location, $route) {
var self = this;
self.tab = function(route) {
return $route.current && route === $route.current.controller;
};
var authenticate = function(credentials, callback) {
var headers = credentials ? {
authorization : "Basic "
+ btoa(credentials.username + ":"
+ credentials.password)
} : {};
$http.get('user', {
headers : headers
}).then(function(response) {
if (response.data.name) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
callback && callback($rootScope.authenticated);
}, function() {
$rootScope.authenticated = false;
callback && callback(false);
});
}
authenticate();
self.credentials = {};
self.login = function() {
authenticate(self.credentials, function(authenticated) {
if (authenticated) {
console.log("Login succeeded")
$location.path("/dashboard");
self.error = false;
$rootScope.authenticated = true;
} else {
console.log("Login failed")
$location.path("/");
self.error = true;
$rootScope.authenticated = false;
}
})
};
self.logout = function() {
$http.post('logout', {}).finally(function() {
$rootScope.authenticated = false;
$location.path("/");
});
}
}).controller('dashboardController', function ($scope, $http, $location) {
$scope.go = function () {
$location.path('/dashboard');
}
});
The login page (index.html) loads fine when I start the server. If I login, the URL changes to "http://localhost:8080/?username=user&password=password" but nothing else happens. Ideally the username and password would not be in the URL....so I would love to know how to eliminate that portion. But the main issues are getting the dashboard.html page to load when authenticated and also to pass the username to the dashboard.html page so I can use it in the context. What am I missing/doing wrong?

simple routing in angularjs

I have the following two files in Angular, wanting to create a simple Login application. The first one is Login.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> AngularJS Login SPA</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="controller.js"></script>
</head>
<body ng-app="mainApp">
<div ng-controller="loginCtrl">
<form action="/" id="myLogin">
Username: <input type="text" name="username" id="username" ng-model="username"><br/>
Password: <input type="password" name="password" id="password" ng-model="password"><br/>
<button type="button" ng-click="submit()">Login</button>
</form>
</div>
</body>
</html>
and the second one is controller.js:
var app = angular.module("mainApp", ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when ('/', {
templateUrl: 'login.html'
})
.when ('#/dashboard',{
resolve:{
"check":function($location, $rootScope){
if (!$rootScope.loggedIn)
{
$location.path('/dashboard');
}
else{
}
}
},
templateUrl: 'dashboard.html'
})
.otherwise ({
redirectTo: '/'
})
});
app.controller('loginCtrl', function($scope, $location, $rootScope){
$scope.submit = function(){
if($scope.username == 'admin' && $scope.password == 'admin')
{
$rootScope.uname = $scope.username;
$rootScope.password = $scope.password;
$rootScope.loggedIn = true;
$location.path('/dashboard');
}
else{
alert('wrong stuff');
}
};
});
The thing is after I succesfully enter the texts 'admin' and 'admin' on username and password (if I click otherwise it correctly shows me an alert), the address changes to .../index.html#/dashboard but it doesn't load me the page dashboard.html, a simple page I created for this app, located in the same folder where index.html is.
Any idea on how it can show me dashboard.html after I succesfully login with the two texts?
Any help could be highly appreciated.
I found out what was the problem.
I had to test the application in Mozilla because Google Chrome doesn't support SPAs (Single Page Applications) that can match a running server.

Resources