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.
Related
I'm trying to code a spring boot application based in Angularjs.
I have a project structure as follows:
The controller calls the index.html perfectly:
the app.js:
var app = angular.module('app', ['ngRoute','ngResource']);
app.config(function($routeProvider){
$routeProvider
.when('/users',{
templateUrl: 'views/users.html',
controller: 'usersController'
})
.when('/roles',{
templateUrl: 'views/roles.html',
controller: 'rolesController'
})
.otherwise(
{ redirectTo: '/'}
);
});
I get the first page when running the app but when I click on the links users and roles, nothing happens.
UPDATED:
the index.html is:
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Spring boot and Angularjs Tutorial</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/css/app.css">
</head>
<body>
<h2>Administrator Panel</h2>
<div class="home-section">
<ul class="menu-list">
<li>Users</li>
<li>Roles</li>
</ul>
</div>
<div ng-view></div>
<script src="/lib/angular.js"></script>
<script src="/lib/angular-resource.js"></script>
<script src="/lib/angular-route.js"></script>
<script src="/js/app.js"></script>
<script src="/js/controller.js"></script>
<link href="/css/bootstrap.css" rel="stylesheet" />
</body>
</html>
How can I fix this issue.
[1]:
For link in AngularJS you should use ng-href directive: https://docs.angularjs.org/api/ng/directive/ngHref
Ex.
<a ng-href="#/users">Users</a>
<ul class="menu-list">
<li><a ui-sref="users">Users</a></li>
<li><a ui-sref="roles">Roles</a></li>
</ul>
Try this one. You can use ui-sref for navigation from html page
Have you declared ng-app="app" at beginning of your template?
Here is how i fixed this issue:
<div class="list-group">
<a href="#home" class="list-group-item"
ng-class="{active: currentNavLink == '/home'}"> <i
class="fa fa-home fa-lg"></i> Home
</a> <a href="#contacts" class="list-group-item"
ng-class="{active: currentNavLink == '/contacts'}"> <i
class="fa fa-user fa-lg"></i> Contacts
</a> <a href="#todos" class="list-group-item"
ng-class="{active: currentNavLink == '/todos'}"> <i
class="fa fa-indent fa-lg"></i> ToDos
</a>
</div>
where in the app.js:
myApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.when('', '/home');
$urlRouterProvider.otherwise('/home');
/*
$urlRouterProvider.rule(function($injector, $location) {
return '/home';
});
*/
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'templates/home.html',
controller: 'HomeController'
})
.state('contacts', {
url: '/contacts',
templateUrl: 'templates/contacts.html',
controller: 'ContactController'
})
.state('todos', {
url: '/todos',
templateUrl: 'templates/todos.html',
controller: 'TodoController'
})
I'm having an issue with the ng-view not display the views when im selecting them from the nav bar. I have this installed on an IIS server, so I'm not sure if there is something I need to change their either.
Config:
angular.module('myApp.controllers').config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'MainWorkQueue.html',
controller: 'MainCtrl'
})
.when('/testingQueue', {
templateUrl: 'TestingQueue.html',
controller: 'testingQueueCntl'
}).otherwise({ redirectTo: '/' });
}]);
Index.html:
<head>
<link rel="stylesheet" type="text/css" href="Content/bootstrap.css">
<script type="text/javascript" src="Scripts/angular.js"></script>
<script type="text/javascript" src="Scripts/angular-animate.js"></script>
<script type="text/javascript" src="Scripts/ui-bootstrap-tpls-2.5.0.min.js"></script>
<script type="text/javascript" src="Scripts/angular-route.js"></script>
</head>
<body ng-app="myApp.controllers">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#/">BuRT</a>
</div>
<ul class="nav navbar-nav">
<li class="active">Main Work Queue</li>
<li>Testing Queue</li>
</ul>
</div>
</nav>
<div ng-view></div>
</body>
When the page loads it loads the MainWorkQueue.html. When I select TestingQueue, the url changes, but the view doesn't.
For some reason when I run a similar code in my browser Not Using IIS it worked notice that I added on <a href=#> is now <a href=#!/> I used !/ for links in angularjs
The first when condition is true because your URL of the /testingQueue has also a /. Changing the URL for your MainWorkQueue.html for example to /main should solve your problem.
And no, the IIS is not involved.
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: '/'
});
}]);
I am new to angular js and following this tutorial http://embed.plnkr.co/dd8Nk9PDFotCQu4yrnDg/ for creating simple SPA page. In which, When I use Local and Session storage concepts in About page ,It is perfectly working in Firefox,IE except Chrome. I am not able to find the problem in Chrome. So Please need your help.
index.html
<html ng-app="scotchApp">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/ngstorage/0.3.6/ngStorage.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="./script.js" type="text/javascript"></script>
</head>
<body ng-controller="mainController">
<header>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">Angular Routing Example</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li><i class="fa fa-home"></i> Home</li>
<li><i class="fa fa-shield"></i> About</li>
<li><i class="fa fa-comment"></i> Contact</li>
</ul>
</div>
</nav>
</header>
<!-- MAIN CONTENT AND INJECTED VIEWS -->
<div id="main">
<div ng-view></div>
</div>
</body>
</html>
pages/about.html:
<div class="jumbotron text-center">
<h1>About Page</h1>
<p>{{ message }}</p>
<input type="button" value="Save" ng-click="Save()" />
<input type="button" value="Get" ng-click="Get()" />
</div>
pages/contact.html:
<div class="jumbotron text-center">
<h1>Contact Page</h1>
<p>{{ message }}</p>
</div>
pages/home.html:
<div class="jumbotron text-center">
<h1>Home Page</h1>
<p>{{ message }}</p>
</div>
scripts.js:
var scotchApp = angular.module('scotchApp',['ngRoute','ngStorage']);
scotchApp.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'pages/home.html',
controller : 'mainController'
})
// route for the about page
.when('/about', {
templateUrl : 'pages/about.html',
controller : 'aboutController'
})
// route for the contact page
.when('/contact', {
templateUrl : 'pages/contact.html',
controller : 'contactController'
});
});
// create the controller and inject Angular's $scope
scotchApp.controller('mainController', function($scope, $localStorage, $sessionStorage, $window) {
// create a message to display in our view
$scope.message = 'Everyone come and see how good I look!';
});
scotchApp.controller('aboutController', function($scope, $localStorage, $sessionStorage, $window) {
$scope.message = 'Look! I am an about page.';
$scope.Save = function () {
$localStorage.LocalMessage = "LocalStorage: My name is Mudassar Khan.";
$sessionStorage.SessionMessage = "SessionStorage: My name is Mudassar Khan.";
$localStorage.$save();
$sessionStorage.$save();
}
$scope.Get = function () {
$window.alert($localStorage.LocalMessage + "\n" + $sessionStorage.SessionMessage);
}
});
scotchApp.controller('contactController', function($scope, $localStorage, $sessionStorage, $window) {
$scope.message = 'Contact us! JK. This is just a demo.';
});
Thanks In advance.
you need to serve your html via a local server .
Now Your files are being served as file:/// it should be http://
refer this stackoverflow answer
I'm going through Scotch.io's MEAN Machine book, and I'm nearly done. Problem is I can't get my Angular code to run correctly——even when I'm literally copying the code from their Github. Whenever I open my app on localhost, ngRoute fails to load (or be injected or whatever) correctly.
Here is my code:
App.js
angular.module('userApp', ['ngAnimate', 'app.routes', 'authService', 'mainCtrl', 'userCtrl', 'userService'])
]);
App.routes
angular.module('app.routes', ['ngRoute'])
.config(function($routeProvider, $locationProvider) {
$routeProvider
//home page route
.when('/', {
templateUrl : 'app/views/pages/home.html'
})
//route for the login page
.when('/login', {
templateUrl : 'app/views/pages/login.html',
controller : 'mainController',
controllerAs : 'login'
});
//get rid of the hash in the URL (url prettification)
$locationProvider.html5Mode(true);
});
mainCtrl.js
angular.module('mainCtrl', [])
.controller('mainController', function($rootScope, $location, Auth) {
var vm = this;
//get user info if logged in
vm.loggedIn = Auth.isLoggedIn();
//check to see if user is logged in ON EVERY REQUEST
$rootScope.$on('$routeChangeStart', function() {
vm.loggedIn = Auth.isLoggedIn();
//get user information on route change
Auth.getUser()
.success(function(data) {
vm.user = data;
});
});
//this function handles the login form
vm.doLogin = function() {
vm.processing = true;
//call the Auth.login() function
Auth.login(vm.loginData.userName, vm.loginData.password)
.success(function(data) {
vm.processing = false;
//if user is logged in, redirect to user page
$location.path('/users');
});
};
//function to handle logging out
vm.doLogout = function() {
Auth.logout();
//reset ALL user info
vm.user = {};
$location.path('/login');
};
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User CRM</title>
<!-- FOR ANGULAR ROUTING -->
<base href="/">
<!-- CSS -->
<!-- load bootstrap from CDN and custom CSS -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootswatch/3.3.1/paper/bootstrap.min.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css">
<link rel="stylesheet" href="assets/css/style.css">
<!-- JS -->
<!-- load angular and angular-route via CDN -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-route.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-animate.js"></script>
<!-- controllers -->
<script src="app/controllers/mainCtrl.js"></script>
<script src="app/controllers/userCtrl.js"></script>
<!-- services -->
<script src="app/services/authService.js"></script>
<script src="app/services/userService.js"></script>
<!-- main Angular app files -->
<script src="app/app.routes.js"></script>
<script src="app/app.js"></script>
</head>
<body ng-app="userApp" ng-controller="mainController as main">
<!-- NAVBAR -->
<header>
<div class="navbar navbar-inverse" ng-if="main.loggedIn">
<div class="container">
<div class="navbar-header">
<span class="glyphicon glyphicon-fire text-danger"></span> User CRM
</div>
<ul class="nav navbar-nav">
<li><span class="glyphicon glyphicon-user"></span> Users</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li ng-if="!main.loggedIn">Login</li>
<li ng-if="main.loggedIn" class="navbar-text">Hello {{ main.user.username }}!</li>
<li ng-if="main.loggedIn">Logout</li>
</ul>
</div>
</div>
</header>
<main class="container">
<!-- ANGULAR VIEWS -->
<div ng-view></div>
</main>
</body>
</html>
This is the exact error I'm receiving:
https://docs.angularjs.org/error/$injector/modulerr?p0=userApp&p1=Error: [$injector:nomod] http://errors.angularjs.org/1.3.8/$injector/nomod?p0=userApp
at Error (native)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:6:416
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:21:366
at a (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:21:7)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:21:250
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:35:424
at s (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:7:302)
at g (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:35:202)
at Ob (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:38:435)
at d (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:17:350
Remove 'userCtrl' from the dependencies in the userApp module in app.js. You may have created that file, but there probably isn't any content. This should do the trick.
I ran into the same problem, the 'userService' dependency in app.js isn't loaded in the index.html file.
To fix this issue add the userService.js file in your index.html file underneath the authService.js file like so:
<!-- services -->
<script src="app/services/authService.js"></script>
<script src="app/services/userService.js"></script>
In your index.html => <body ng-app="userApp" so you need add to your mainCtrl.js look like this:
angular.module('userApp.mainCtrl', [])
You also need do the same way to userCtrl.js, authService.js, userService.js and app.routes.js.
Now in your App.js finally may look like this:
angular.module('userApp', ['ngAnimate', 'userApp.Routes', 'userApp.authService', 'userApp.mainCtrl', 'userApp.userCtrl', 'userApp.userService'])
]);
Edit
I try your code in plunker but with commenting <base href="/"> and change
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
for it work in plunker. Here (http://embed.plnkr.co/BHyE6iWDN5uXqiitaMDU/preview) you can visit it with same error in console log. It's seem due to fail load some depedencies which i left empty at some file.
Here (http://embed.plnkr.co/eD4TYgMNq4MDHQZ7p3n0/preview) another plunker that you can see the error has gone, all of depedencies success loaded. Make sure you have correct typo & not missing the depedencies.