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

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']
});

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>

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

templateUrl is not being called by angular $routeProvider

I am learning AngularJs now a days and stuck in the error and couldn't resolve it for the last two days. First let's look at my code first:
MainPage.html
<!DOCTYPE html>
<html>
<head>
<title>Learn Angular Js - Scott Allen</title>
<meta charset="utf-8" />
</head>
<body ng-app="LearnAngular">
<h1>Git Hub Viwer</h1>
<div ng-view></div>
<script src="angular.js"></script>
<script src="angular-route.js"></script>
<script src="App.js"></script>
<script src="MainController.js"></script>
</body>
</html>
App.js
(function () {
var app = angular.module("LearnAngular", ["ngRoute"]);
app.config(function routeConfig($routeProvider) {
$routeProvider
.when("/main", {
templateUrl: function () {
debugger;
return "Main.html";
},
controller: "MainController"
})
.otherwise({ redirectTo: "/mian" });
});
}());
MainController.js
(function () {
var MainController = function ($scope, $interval, $location) {
alert("var MainController = function ($scope, $interval, $location) {};");
var decrementCountdown = function () {
$scope.countdown -= 1;
if ($scope.countdown < 1) {
$scope.search($scope.username);
}
};
var countDownPromise = null;
var startCountdown = function () {
countDownPromise = $interval(decrementCountdown, 1000, $scope.countdown);
};
$scope.search = function (username) {
if (countDownPromise) {
$interval.cancel(countDownPromise);
$scope.countdown = null;
}
// redirect to the url.
};
$scope.username = "angular";
$scope.countdown = 5;
startCountdown();
};
var app = angular.module("LearnAngular");
app.controller("MainController", MainController);
}());
Main.html
<div>
<h1>{{countdown}}</h1>
<form name="searchUser" ng-submit="search(username)">
<input type="search" required placeholder="Enter username to search" ng-model="username" />
<input type="submit" value="Search" />
</form>
</div>
When I run the application, i see this url:
http://localhost:52108/HomePage.html#/mian
which shows that I successfully redirect to the main route but Main.html is not being shown on the HomePage.html page and browser is not requesting for the Main.html when I examine the network of browser.
Here is the screen shot of my application:
I searched on the internet and tried many solutions but none of them solves my problem. I don't what is wrong with the code. I am developing in VisualStudio
Thanks in advance for your help and time.
You had typo in URL there in otherwise's redirectTo value, it should be /main
.otherwise({ redirectTo: "/main" });

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.

Resources