AngularJS - Route to another page of different ng-app module after login - javascript

I have a basic knowledge of AngularJS only. I have created one AngularJS application.
index.html has two links for login and register. With ng-view. By default, login is the view. In the login view I have form. That will be posting to servlet and return the status with object. I have another page home.html wis=ch has its own ng-app module. When the login is success, I want to route to home.html pgae. It also has two links and one ng-view to display the links.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login - AngularJS</title>
<link rel="stylesheet" type="text/css" media="all" href="styles/angulardemo.css" />
<script src="script/angular.min.js"></script>
<script src="script/app.js"></script>
<script src="script/loginController.js"></script>
</head>
<body data-ng-app="sampleApp">
<div class="index container">
<div class="row">
<div class="">
<ul class="nav">
<li> Login </li>
<li> View1 </li>
</ul>
</div>
<div class="loginView">
<div ng-view></div>
</div>
</div>
</div>
</body>
</html>
login.html
<h2>Login</h2>
<form ng-submit="loginUser()">
<fieldset>
<legend>Login</legend>
<label>Name: </label> <input type="text" id="name" name="name"
ng-model="user.name" placeholder="User Name" required="required">
<br> <label>Password:</label> <input
type="password" id="password" name="password"
ng-model="user.password" placeholder="Your Password"
required="required"> <br>
<button class="btn btn-primary">Login</button>
<br />
</fieldset>
<label>{{user.status}}</label>
</form>
app.js
//Define Routing for app
angular.module('sampleApp', []).config(['$routeProvider',
function($routeProvider,$locationProvider) {
$routeProvider
.when('/login', {
templateUrl: 'login.html',
controller: 'LoginController'
})
.when('/register', {
templateUrl: 'register.html',
controller: 'RegisterController'
})
.otherwise({
redirectTo: '/login'
});
// $locationProvider.html5Mode(true); //Remove the '#' from URL.
}]);
//Home Page Module
angular.module('homeApp', []).config(['$routeProvider',
function($routeProvider,$locationProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html'
})
.when('/profile', {
templateUrl: 'profile.html',
controller: 'ProfileController'
})
.when('/settings', {
templateUrl: 'settings.html',
controller: 'SettingsController'
})
.otherwise({
redirectTo: '/home'
});
// $locationProvider.html5Mode(true);
}]);
LoginController (has both login and register. I have implemented only for login)
angular.module('sampleApp').controller('LoginController', function($scope,$location,$http) {
$scope.user = {};
$scope.loginUser = function()
{
$http({
method: 'POST',
url: 'http://localhost:8080/AngularJSLogin/login',
headers: {'Content-Type': 'application/json'},
data: $scope.user
}).success(function (data)
{
var strJSON=data;
if(strJSON.status=="Success")
{
alert("success");
$location.path( "/home" );
}
else
{
$scope.user.status=strJSON.userId+" : "+strJSON.status;
}
});
};
});
angular.module('sampleApp').controller('RegisterController', function($scope,$location,$http) {
$scope.user = {};
});
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login - AngularJS</title>
<link rel="stylesheet" type="text/css" media="all" href="styles/angulardemo.css" />
<script src="script/angular.min.js"></script>
<script src="script/loginController.js"></script>
<script src="script/userController.js"></script>
</head>
<body data-ng-app="homeApp">
<div class="container">
<div class="row homeTitle">
<div class="username">
<h3>{{user.name}}</h3>
</div>
<div class="homeMenu">
<ul class="nav">
<li> Profile </li>
<li> Settings </li>
</ul>
</div>
</div>
<div class="">
<div ng-view></div>
</div>
</div>
</body>
</html>
Each link has its own controllers.
When I click on the login button with valid username and pasword, It is alerting with Success, but not going to the home (home.html) page.
How can I route to a different page that has different ng-app module from another one? And also how to pass this User object to home.html ng-app module, so it can have user data and display the user name, and other values?

I know this is over 2 years old and i'm sure you might have moved past this but i'm going to tell you how i did as i have a similar set up. Doing everything on the client side wont do it for you. You need to offload some of that routing logic to the server-side. Others might be suggesting using only one ng-app throughout your application but for me that was not a requirement. multi app was a necessity.
My application consisted of 6 ng-apps sharing some common modules and services. each with its own responsibility for e.g I had one like yours with views for login, signup and password-reset while the others were "protected ng-apps".
The trick to get mine working was with the login request. I dont return 200 json back on successful login from the server, I just redirect to the main page i.e I serve the protected main ng-app on successful login. Then i set a httpOnly Cookie with the user information serialized as a JWT String.
Point is...treat every angular application as one page and have your server-side code decide what to show based on your auth rules.
Hope this helps anyone using model :)

We can add many ng-view tags in as many div but it will paste whatever routes mandate to be pasted to the dom.

As I know only one ng-app can be used per html document and same is true for the ng-view also.
The idea I would suggest you to use $routeProvider to navigate between pages in the application.
Use services to have the login information of the user and also have ng-show/ng-hide to show them particular pages based upon their login state.

Related

Can not get grandchild state to work with UI Router

I am using Angular 1.6.2 and UI Router. I am still trying to learn the concepts correctly, but have come to a road block.
I have a parent state called app using MainController, and a bunch of child states. However I now want to go one level deeper by making grandchild states.
The following codes leaves me with a blank page when loading www.example.com/manage-users/edit/1 thus not loading the grandparent state.
However it does work if I make app a parent of edit-users (the one I want to make a third level deep), but thats not really the correct way of going about it. Because after this I need to use the parent states for other reasons.
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<base href="/">
// loading JS/CSS etc
</head>
<body ng-app="sampleApp">
<div class="container">
<div ui-view></div>
</div>
</body>
</html>
parent.html
<div ng-controller="MainController as data">
// more html
<div ui-view></div>
</div>
manage-users.html
<div class="col-sm-12" ng-controller="UserController as data">
// more html
<div ui-view></div>
</div>
manage-users-edit.html (only works when I make the parent state 'app' instead of 'manage-users'
<div>Hello World! This is the Edit HTML Page</div>
app.js setting up states
$stateProvider
.state('app', {
templateUrl: 'views/parent.html',
controller: 'MainController as data'
})
.state('manage-users', {
parent: 'app',
url: '/manage-users',
templateUrl: 'views/manage-users.html',
controller: 'MainController as main'
})
.state('edit-users', {
parent: 'manage-users',
url: '/manage-users/edit/:id',
templateUrl: 'views/manage-users-edit.html',
controller: 'MainController as main'
});
Try this:
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<base href="/">
// loading JS/CSS etc
</head>
<body ng-app="sampleApp">
<div class="container" ui-view="container"></div>
</body>
</html>
parent.html
<div ng-controller="MainController as data">
// more html
<div ui-view="parent"></div>
</div>
manage-users.html
<div class="col-sm-12" ng-controller="UserController as data">
// more html
<div ui-view="manageusers"></div>
</div>
app.js
$stateProvider
.state('app', {
views:{
'container': {
templateUrl: 'views/parent.html',
controller: 'MainController as data'
}
}
})
.state('app.manage-users', {
url: '/manage-users',
views:{
'parent':{
templateUrl: 'views/manage-users.html',
controller: 'MainController as main'
}
}
})
.state('app.manage-users.edit-users', {
url: '/edit/:id',
views:{
'manageusers':{
templateUrl: 'views/manage-users-edit.html',
controller: 'MainController as main'
}
}
});
You should always navigate to the child of your hierarchy. In this case, $state.go('app.manage-users.edit-users')
EDIT:
Your URL property in state config is wrong. To hit what you expect, you should enter http://exapmle.com/#/manage-users/edit/1.
I have updated the config, so extra manage-users from the URL is removed. Give it a shot.

AngularJS Routing doesn't work properly

I need help with routing in AngularJS. I am new and don't understend why it doesn't work.
I have a small application with to pages.
my app.js:
var app = angular.module("suggestionBox", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'HomeController',
templateUrl: 'views/home.html'
})
.when('/suggestion/:id', {
controller: 'SuggestionController',
templateUrl: 'views/suggestion.html'
})
.otherwise({
redirectTo: '/'
});
});
my view:
<form ng-submit="addSuggestion()" style="margin-top: 50px">
<h3> Submit Your Suggestion </h3>
<div class="form-group">
<input type="text" class="form-control" placeholder="Great ideas here" ng-model="data.title">
</div>
<button type="submit" class="btn btn-primary">Suggest</button>
</form>
<div class="posts-wraper">
<div class="suggestion" ng-repeat="post in posts | orderBy: '-upvotes'">
<h3>{{ post.title }}</h3>
<div>
<p>
<span class="glyphicon glyphicon-plus-sign" ng-click="upVote(post)"></span> Upvotes: {{post.upvotes}}
</p>
<a class="comment" href="#/suggestion/{{$index}}">Comments</a>
</div>
</div>
</div>
main page:
<!DOCTYPE html>
<html>
<head>
<title>Suggestion Box</title>
<script type="text/javascript" src="js/vendor/angular.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<script src="https://code.angularjs.org/1.2.28/angular-route.min.js"></script>
</head>
<body ng-app="suggestionBox">
<div class="col-md-2"></div>
<div class="col-md-8">
<div ng-view></div>
</div>
<div class="col-md-2"></div>
<!-- Modules -->
<script type="text/javascript" src="js/app.js"></script>
<!-- Controllers -->
<script type="text/javascript" src="js/controllers/HomeController.js"></script>
<script type="text/javascript" src="js/controllers/SuggestionController.js"></script>
<!-- Services -->
<script src="js/services/suggestions.js"></script>
</body>
</html>
And when I'm on home page and want to go to /suggestion/:id I click reference and nothing happen. But I have the following url: "http:// localhost:8080/#!/#suggestion%2F0" and stay at the home page. If I type url by hand like this: "http:// localhost:8080/#!/suggestion/0" all is well and I go to suggestion page. Then I press back:
Back
and it works! I am on home page, but url is: "http:// localhost:8080/#!/#%2F"
I don't know why! Please help me with it.
How about something like that check the Plunker if code snippet doesn't make any sense also pay attention to markup changes in the index, home and suggestion.html in plunker. You can edit the plunker and see the URL changes by launching the plunker preview in separate window.
app.js
var app = angular.module("SuggestionBox", ['ngRoute']);
app.config(["$routeProvider", "$locationProvider", function($routeProvider, $locationProvider){
$locationProvider.hashPrefix(''); // magic line
$routeProvider
.when('/',{
controller: "HomeController",
templateUrl: "views/home.html"
})
.when('/suggestion/:id',{
controller: "SuggestionController",
templateUrl: "views/suggestion.html"
})
.otherwise({
redirectTo: '/'
});
}]);

Angular not routing properly. URL is localhost:8081/#!/#pageName

I am making a simple Angular application that has an index.html which loads other HTML pages as views based on which navbar item selected; however, the routing is not working as expected. The main.html view is loaded fine, but none of the other views are loaded, and the URL is not what I expect.
The URL that shows up in the browser after an item is selected is localhost:8081/#!/#pageName. I do not know where the '!' is coming from, and there should not be a hash before the pageName. The URL that I am expecting is localhost:8081/#/pageName
app.js:
'use strict';
var app = angular.module('videoGamesApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/rankedLists', {
templateUrl: 'views/rankedLists.html',
controller: 'RankedListsCtrl'
})
.when('/addGame', {
templateUrl: 'views/addGame.html',
controller: 'AddGameCtrl'
})
.when('/contact', {
templateUrl: 'views/contact.html',
controller: 'ContactCtrl'
})
.otherwise({
redirectTo: '/'
});
});
app.controller('MainCtrl', function($scope) {
$scope.message = 'THIS IS THE MAIN PAGE';
});
app.controller('RankedListsCtrl', function($scope) {
$scope.message = 'THIS IS THE RANKED LISTS PAGE';
});
app.controller('AddGameCtrl', function($scope) {
$scope.message = 'THIS IS THE ADD GAME PAGE';
});
app.controller('ContactCtrl', function($scope) {
$scope.message = 'THIS IS THE CONTACT PAGE';
});
index.html:
<!doctype html>
<html ng-app="videoGamesApp">
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="styles/main.css">
<link rel="stylesheet" href="../bower_components/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="../bower_components/font-awesome/css/font-awesome.css">
</head>
<body ng-controller="MainCtrl">
<header>
<nav class="navbar navbar-inverse">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">GAMING </a>
</div>
<ul class="nav navbar-nav">
<li><i class="fa fa-home"></i> Home</li>
<li><i class="fa fa-trophy"></i> Ranked Lists</li>
<li><i class="fa fa-gamepad"></i> Add a Game</li>
<li><i class="fa fa-comment"></i> Contact</li>
</ul>
<div class="col-sm-3 col-md-3 pull-right">
<form class="navbar-form" role="search">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name="sr ch-term">
<div class="input-group-btn">
<button class="btn btn-default" type="submit">
<i class="glyphicon glyphicon-search"></i>
</button>
</div>
</div>
</form>
</div>
</div>
</nav>
</header>
<div id="main">
<div ng-view=""></div>
</div>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="scripts/app.js"></script>
</body>
</html>
Why are the other views not loading? Where is the exclamation point coming from in the URL? Why is there a hash before the pageName (I expect one hash, not two).
Why are the other views not loading?
The reason why your views are not loaded is because you hit the route. You use 1.6 angular and expect the behaviour from 1.5. There has been a change in location hash-prefix:
Due to aa077e8, the default hash-prefix used for $location hash-bang
URLs has changed from the empty string ('') to the bang ('!'). If your
application does not use HTML5 mode or is being run on browsers that
do not support HTML5 mode, and you have not specified your own
hash-prefix then client side URLs will now contain a ! prefix. For
example, rather than mydomain.com/#/a/b/c the URL will become
mydomain.com/#!/a/b/c.
If you actually want to have no hash-prefix, then you can restore the
previous behavior by adding a configuration block to you application:
appModule.config(['$locationProvider', function($locationProvider) {
$locationProvider.hashPrefix(''); }]); Source
What to do?
1. Set HTML5mode true
$locationProvider.html5Mode(true);
and in html set base in html header:
<base href="/">
Lastly change <a ng-href="#pagename"> to
<a ng-href="pagename">
2. Go back to old behaviour from 1.5 - set hash prefix manually
This will make your app work as you expect in your question.
app.config(['$locationProvider', function($locationProvider) {
$locationProvider.hashPrefix('');
}]);
Why is there a hash before the pageName?
The way you link is treated as a hashtag anchor tag. Which will scroll down to the current div with the given id. If you fix your problem with one of the above reasons this will be fixed aswell.

Angularjs - Controller call init() function multiple times

I have a problem while I'm making an angularjs app.
I create a controller and bind it in routeProvider. With a function to initialize values for the controller like this.
angular.module('app.Login', ['app.rpc','ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {
templateUrl: '/static/tour/app/login/login.html',
controller: 'loginController'
});
}])
.controller('loginController', function($scope, $location, rpc) {
$scope.init = function() {
$scope.error = "";
console.log("Login Initialized");
}
$scope.init();
});
for login.html like this
<div class="container">
<div class="row">
<div class="col-xs-12">
<h1 class="page-header">Login</h1>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="alert alert-danger alert-dismissable" role="alert" ng-show="error">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Error: </strong>
<span>{{error}}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<form>
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" ng-model="username" placeholder="Username">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" ng-model="password" placeholder="Password">
</div>
<button class="btn btn-primary action-btn" ng-click="login()">Login</button>
</form>
</div>
</div>
</div>
When I run the app, it call init() 3 times like this.
login
Find out in this stackoverflow that many people also get this troble. All of them solved by make sure that controller doesn't bind more than one time (in routProvider and in template), and check that only one ng-app in the template.
My main html like this.
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="UTF-8">
<title>Touring</title>
<!--Bootstrap-->
<link rel="stylesheet" href="/static/tour/css/bootstrap.min.css">
<link rel="stylesheet" href="/static/tour/css/bootstrap-theme.min.css">
<!--/Bootstrap-->
</head>
<body>
<ng-view><ng-view>
<!--Angular-->
<script src="/static/tour/js/angular.min.js"></script>
<script src="/static/tour/js/angular-route.min.js"></script>
<script src="/static/tour/js/angular-cookies.min.js"></script>
<!--/Angular-->
<!--App-->
<script src="/static/tour/app/app.js"></script>
<script src="/static/tour/app/rpc/app-rpc.js"></script>
<script src="/static/tour/app/login/app-login.js"></script>
<script src="/static/tour/app/dashboard/app-dashboard.js"></script>
<script src="/static/tour/app/memo/app-memo.js"></script>
</body>
</html>
For my main app like this.
angular.module('app',
['ngCookies',
'ngRoute',
'app.Login',
'app.Dashboard',
'app.Memo',
])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
resolve: {
"check": function($cookies, $location) {
if(!$cookies.get("user_id")) {
$location.path("/login");
}
else {
$location.path("/dashboard");
}
}
}
})
.when('/logout', {
resolve: {
"check": function($cookies, $location) {
if($cookies.get("user_id")){
alert("You have been Logout");
}
$cookies.remove("user_name");
$cookies.remove("user_id");
$cookies.remove("token");
$cookies.remove("dbname");
$location.path("/login");
}
}
});
}]);
It ok for this controller, I just want to initialize a text but it's not ok for init in some controller that need some AJAX request to server side, could make too many request for noting. Anyone can solve this please help me. Thanks.
PS1. My practice base on angular-seed https://github.com/angular/angular-seed
PS2. At first, I also used jquery and it show WARNING: Tried to load angular more than once. Once I remove jquery it never show warning again, but it didn't fix my problem
I already solve it
<ng-view><ng-view>
use this instead
<div ng-view></div>
Concerning your multiple method call, are you sure your current URL is exactly the same as defined in the $routeProvider config? (maybe ngRoute redirects from /login/ to /login and calls your controller twice)
PS2. At first, I also used jquery and it show WARNING: Tried to load angular more than once. Once I remove jquery it never show warning again, but it didn't fix my problem
AngularJS already contains a lite version of jQuery: jqLite. If jQuery is loaded before Angular, this last one will use it. If not, it use the built-in lite version.
In your case, the error is probably due to a jQuery loading after the Angular loading. Angular already loads its version and you load it again.
Try to load jQuery before Angular or do not load it at all.

AngularJS "Controller as" in templates

I am new to AngularJS world and I am trying to setup a basic laravel/angular JWT auth following this tutorial.
What I'd like to do, it's to use the "Controller As" syntax instead of the $scope as stated in the tutorial. For now, here what I have:
app.js
var app = angular.module('app', ['ngRoute']);
app.run(function () {});
app.config(function ($routeProvider, $locationProvider) {
$routeProvider.when('/', {
templateUrl: 'js/templates/login.html',
controller: 'LoginController'
});
});
login controller
angular.module('app')
.controller('LoginController', function ($scope) {
this.title='toto';
this.data = {};
this.submit = function () {
console.log(this.data);
};
});
admin view
<!doctype html>
<html lang="en">
<head>
<title>Blog Administration</title>
<!--css-->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"/>
<!--js-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!--angular-->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/loginController.js"></script>
</head>
<body ng-app="app">
<div id="wrapper">
<div class="container" id="view" ng-view>
</div>
</div>
</body>
</html>
login template
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body ng-controller="LoginController as login">
<div class="container">
<div id="login" class="col-md-4 col-md-offset-4">
<div id="login-form">
<h4>{{ login.title }}</h4>
<form ng-submit="login.submit()"><!--username-->
<div class="form-group">
<input id="username" type="text" ng-model="login.data.username"/>
</div>
<!--password-->
<div class="form-group">
<input id="password" type="password" ng-model="login.data.password"/>
</div>
<!--submit-->
<div class="form-group">
<button class="btn btn-primary" type="submit">Login</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
The problem is that nothing renders. Is it possible to use a controller per template ?
If I put the <ng-controller="LoginController as login"> directive in the view body instead of template everything renders correctly.
Is it a good practice to define a controller per template ? Because the login template should be as generic as possible, so it can be loaded in any view if the user isn't authenticated, that's why I think putting login() action in the controlelr handling the Admin view is wrong.
Can someone advice me on the best practices to have here ?
In order to use controllerAs syntax with routeProvider you need to declare additional property in route configuration:
$routeProvider.when('/', {
templateUrl: 'js/templates/login.html',
controller: 'LoginController',
controllerAs: 'login'
});
Then you need to clean up login template, removing everything but actual template, e.g. no HTML, body tags, etc. You also don't need extra ngController directive in partial template:
<div id="login" class="col-md-4 col-md-offset-4">
<div id="login-form">
<h4>{{ login.title }}</h4>
<form ng-submit="login.submit()">
<!--username-->
<div class="form-group">
<input id="username" type="text" ng-model="login.data.username" />
</div>
<!--password-->
<div class="form-group">
<input id="password" type="password" ng-model="login.data.password" />
</div>
<!--submit-->
<div class="form-group">
<button class="btn btn-primary" type="submit">Login</button>
</div>
</form>
</div>
</div>
Question 1: Is it possible to use a controller per template ?
Ans: Yes. Its very simply. How, is shown in next answer.
Question 2: Is it a good practice to define a controller per template ?
Ans: As per the AngularJs shown rules, Its good practice. Now see the 2
different way of defining the controller for the template.
a. Directly into the template like: <div ng-controller="myCtrl">Whole template
data goes inside this div.</div>
b. from the app.js where we load the template like this:
.state('app.products.all', {
url: '/all',
templateUrl: 'tpl/products/blocks/thumb.html',
controller: 'ProductsAllCtrl'
})
Here i have also shown the controller with the template path. Second way is
more better then the first.

Categories

Resources