simple routing in angularjs - 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.

Related

Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.9/$injector/modulerr

I am new to AngularJs and try my first project into it. Using Angular.min.js and angular-route.js 1.6.9 version. While hitting the http://localhost/myAngular/login/main.html in browser getting Uncaught Error:
[$injector:modulerr] http://errors.angularjs.org/1.6.9/$injector/modulerr?p0=myApp&p1=ReferenceError%3A%20otherwise%20is%20not%20defined%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%2FmyAngular%2Flogin%2Fmain.html%3A32%3A2%0A%20%20%20%20at%20Object.invoke%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.9%2Fangular.min.js%3A44%3A390)%0A%20%20%20%20at%20d%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.9%2Fangular.min.js%3A42%3A279)%0A%20%20%20%20at%20https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.9%2Fangular.min.js%3A42%3A418%0A%20%20%20%20at%20r%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.9%2Fangular.min.js%3A8%3A7)%0A%20%20%20%20at%20g%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.9%2Fangular.min.js%3A42%3A180)%0A%20%20%20%20at%20gb%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.9%2Fangular.min.js%3A46%3A250)%0A%20%20%20%20at%20c%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.9%2Fangular.min.js%3A22%3A19)%0A%20%20%20%20at%20Uc%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.9%2Fangular.min.js%3A22%3A332)%0A%20%20%20%20at%20we%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.9%2Fangular.min.js%3A21%3A1)
main.html:
<!DOCTYPE html>
<html lang="Eng">
<head>
<title>Login Demo</title>
<script src="angular.min.js"> </script>
<script src="angular-route.js"></script>
<script src="controller.js"></script>
</head>
<body ng-app="mainApp">
<div ng-view>
</div>
</body>
controller.js
var app = angular.module( 'mainApp', ['ngRoute'] );
app.config( function( $routeProvider ) {
$routeProvider
.when( '/main', {
template: 'Welcome User!'
//templateUrl: 'login.html'
})
.when('/anotherPage', {
template: 'Welcome User, again!'
//templateUrl: 'dashboard.html'
})
otherwise({
redirectTo: '/'
});
});
app.controller( 'loginCtrl', function( $scope, $location) {
$scope.submit = function(){
var userName = $scope.userName;
var password = $scope.password;
if(userName == "admin" && password == "admin"){
$location.path = '/dashboard';
}
console.log( userName +" "+ password);
};
});
===========================================================
login.html
<div ng-controller="loginCtrl">
<div>
<form action="/" id="myLogin">
User Name: <input type="text" name="userName" ng-model="userName"/>
<br>br>
Password: <input type="password" name="password" ng-model="password"/>
<br><br>
<button type="button" ng-click="submit()">Submit</button>
</form>
</div>
</div>
Try:
$routeProvider
.when( '/main', {
template: 'Welcome User!'
//templateUrl: 'login.html'
})
.when('/anotherPage', {
template: 'Welcome User, again!'
//templateUrl: 'dashboard.html'
})
.otherwise({ // <-- you were missing "." here.
redirectTo: '/'
});
});
Also, try to use "angular.js" rather than angular.min.js , you'll get readable and easily understandable error messages
Side Note: Try to use controller in $routeProvider itself rather than writing it the way you have written in login.html. Refer the config of my plunkr
Here is the working code
Update
As per your new code, you need to do as below
$location.path('/dashboard');
Refer the plunkr. I have made the respective changes in it too

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>

Angular route is not working in my web application

Angular Router is not working in my application. I have a login form, Angular controller, and Welcome page. When I pass the login details and click on submit button, Angular is not routing to welcome.html page.
Below is the code snippet.
Login Form(AngularForm.html)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-route.js"></script>
<script src="LoginCtrl.js"></script>
</head>
<body ng-app="myAngular">
<div ng-controller="LoginController">
<form action="/" id="myForm">
UserName:
<input type="text" id="username" ng-model="username">
<br> Password:
<input type="password" id="passowrd" ng-model="password">
<br>
<button type="button" ng-click="submit()">Login</button>
</form>
</div>
</body>
</html>
Login Controller(LoginCtrl.js)
var App = angular.module('myAngular', ['ngRoute']);
App.config(function($routeProvider){
$routeProvider.when('/',{
templateUrl: 'AngularForm.html'
})
.when('/welcome',{
templateUrl: 'welcome.html'
})
.otherwise({
redirectTo: '/'
});
});
function UserLogin($scope,$location)
{
$scope.submit = function(){
var uname=$scope.username
var pwd=$scope.passowrd
if($scope.username == 'admin' && $scope.password == 'admin')
{ $location.path('/welcome'); }
}
}
App.controller('LoginController',UserLogin);
Welcome Page(welcome.html)
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Login Successful!!</h1>
</body>
</html>
I think you need to separate the login content from the main AngularForm.html file
AngularForm.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-route.js"></script>
<script src="LoginCtrl.js"></script>
</head>
<body ng-app="myAngular">
<div ng-view></div>
</body>
</html>
make sure to add the <div ng-view></div> so that partial routes lay on top of this.
make the login HTML like this
login.html
<div ng-controller="LoginController">
<form action="/" id="myForm">
UserName:<input type="text" id="username" ng-model="username"><br>
Password:<input type="password" id="passowrd" ng-model="password"><br>
<button type="button" ng-click="submit()">Login</button>
</form>
</div>
add a new state called login in the config
JS
var App = angular.module('myAngular', ['ngRoute']);
App.config(function($routeProvider){
$routeProvider
.when('/',{
templateUrl: 'AngularForm.html'
})
.when('/login',{
templateUrl: 'login.html'
})
.when('/welcome',{
templateUrl: 'welcome.html'
})
.otherwise({
redirectTo: '/login'
});
});
function UserLogin($scope,$location)
{
$scope.submit = function(){
var uname=$scope.username
var pwd=$scope.passowrd
if($scope.username == 'admin' && $scope.password == 'admin')
{ $location.path('/welcome'); }
}
}
App.controller('LoginController',UserLogin)

Angular Routing is not working after logging in

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.

AngularJS simple Loginform

I've just started to build a prototype in AngularJs/Bootstrap. I'm new to angular but it seem interesting enough to evaluate for some upcoming webprojects.
Step 1 would be to get some simple Loginform to work with hardcoded values and not bother to communicate with the backend service.
However, I read a bunch of tutorials but can't get the routing to work, the mysterious variable $location is always undefined no matter how many times I pass it around. Is perhaps the use of it old-fashioned? I tried some examples from this site but none works, $location is'nt among us anymore it seems?
Last example I tried:
angular.module('myApp.controllers', []).
controller('loginController', ['$scope', function($scope, $route, $routeParams, $location) {
$scope.auth = function() {
//check something useful
$location.url('/view2');
};
}])
If someone has a simple and working example (or an url for a trusted source of information) of a form and a controller that use routing to another partial, I would be delighted.
Regards
I have been struggling with the same issue. I posted this question. The answer shed some light. I was then able to force users to login and only then will they be able to access other links on the navbar. Then I had the issue of nav bar being visible on the login screen. So I created a work-around:
1) I split the pages: using ng-include I was able to load login.html by default. login.html and index.html does not have ng-view.
2) Once the user is authenticated, ng-view must be inlcuded so that all views required on the navigation can work
index.html
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="style.css" />
<script src="angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="AppCtrl">
<div ng-include="template.url"></div>
</body>
</html>
login.html
<h1>Login Page</h1>
<form ng-submit="login(username, password)">
<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>
Then if authentication passes I change templates (ng-include) and make home.html the default page
app.controller('AppCtrl', function($scope, authentication) {
$scope.templates =
[
{ url: 'login.html' },
{ url: 'home.html' }
];
$scope.template = $scope.templates[0];
$scope.login = function (username, password) {
if ( username === 'admin' && password === '1234') {
authentication.isAuthenticated = true;
$scope.template = $scope.templates[1];
$scope.user = username;
} else {
$scope.loginError = "Invalid username/password combination";
};
};
};
Home.html has ng-view which will do the usual and the user has access to other pages.
This is what I have so far, here is a working example, hope it helps.
This would work:
controller('loginController', ['$scope', '$route', '$routeParams', '$location', function($scope, $route, $routeParams, $location) {
$scope.auth = function() {
//check something useful
$location.url('/view2');
};
}])
Each resource you want to inject into your controller should be passed as a string in the array.

Resources