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: '/'
});
}]);
Related
I am very new in angular JS and ng-view is not working.
Below is code of AngularFormsApp.js
var angularFormsApp = angular.module('angularFormsApp', ["ngRoute"]);
angularFormsApp.config(function ($routeProvider) {
$routeProvider
.when("/home", {
templateUrl: "app/Home.html",
controller: "HomeController"
})
.when("/newEOIForm", {
templateUrl: "app/EOIForm/eoifTemplate.html",
controller: "eoifController"
})
.otherwise({
redirectTo: "/Home"
});
});
angularFormsApp.controller("HomeController",
function ($scope, $location) {
$scope.addNewEOI = function () {
$location.path('/newEOIForm');
};
});
Below is html code.
<!DOCTYPE html>
<html ng-app="angularFormsApp">
<head>
<title></title>
<link href="Content/bootstrap.min.css" rel="stylesheet" />
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/angular-route.min.js"></script>
<script src="app/AngularFormsApp.js"></script>
<script src="app/EOIForm/eoifController.js"></script>
<script src="app/EOIForm/eoifDirective.js"></script>
<script src="app/EOIForm/eoifService.js"></script>
</head>
<body ng-controller="eoifController" class="container">
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="nav">
Home
About
Detail
</div>
</div>
</div>
</div>
<div class="container">
<div ng-view=""></div>
</div>
</body>
</html>
Below is my root structure.
Why ng-view is not working, also I am not able to debug the code.
Be careful with that $routeProvider.otherwise({redirectTo: '/Home'}).
It should be:
$routeProvider.otherwise({redirectTo: '/home'})
Please, link the href in your index.html like this:
Home
About
Detail
And in your config:
angularFormsApp.config(function ($routeProvider) {
$locationProvider.hashPrefix('');
// Rest of the code
I'm doing a tutorial from https://thinkster.io/tutorials/mean-stack called flapper news. I have completed the tutorial and the system work fine. But, I was thinking doing an inline template in a single file is not a good practice specially if you're doing a big project. So I tried to separate those templates into files(.html). Unfortunately the html file cannot be displayed in the ui-view. There was no error in the console nor the server. I tried to change my index.ejs file in the view folder into the public folder and rename it to index.html. Still not working.
Here is my index.html:
<html>
<head>
<title>Flapper News</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>
<script src="/javascripts/angularapp.js"></script>
<style>
.glyphicon-thumbs-up {
cursor: pointer
}
</style>
</head>
<body ng-app="flapperNews">
<nav class="navbar navbar-default pull-right" ng-controller="NavCtrl">
<ul class="nav navbar-nav">
<li ng-show="isLoggedIn()"><a>{{ currentUser() }}</a></li>
<li ng-show="isLoggedIn()">Log Out</li>
<li ng-hide="isLoggedIn()">Log In</li>
<li ng-hide="isLoggedIn()">Register</li>
</ul>
</nav>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<ui-view></ui-view>
</div>
</div>
</body>
</html>
Here is one of the html file in the same public folder(home.html):
<script type="text/ng-template" id="/home.html">
<div class="page-header">
<h1>Flapper News</h1>
</div>
<div ng-repeat="post in posts | orderBy: '-upvotes'">
<span class="glyphicon glyphicon-thumbs-up" ng-click="incrementUpvotes(post)"></span> {{post.upvotes}}
<span ng-show="post.author"> posted by <a>{{post.author}}</a> |
</span>
<span style="font-size:20px; margin-left:10px;">
<a ng-show="post.link" href="{{post.link}}">
{{post.title}}
</a>
<span ng-hide="post.link">
{{post.title}}
</span>
</span>
<span>
Comments
</span>
</div>
<form ng-submit="addPost()" ng-show="isLoggedIn()" style="margin-top:30px;">
<div ng-hide="isLoggedIn()">
<h3>You need to Log In or Register before you can add a post.</h3>
</div>
<h3>Add a new post</h3>
<div class="form-group">
<input type="text" class="form-control" placeholder="Title" ng-model="title"></input>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Link" ng-model="link"></input>
</div>
<button type="submit" class="btn btn-primary">Post</button>
</form>
</script>
public/javascripts/angularApp.js:
var app = angular.module('flapperNews', ['ui.router']);
app.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/',
templateUrl: 'home.html',
controller: 'MainCtrl',
resolve: {
postPromise: [
'posts',
function(posts) {
return posts.getAll();
}
]
}
})
.state('posts', {
url: '/posts/{id}',
templateUrl: '/posts.html',
controller: 'PostsCtrl',
resolve: {
post: [
'$stateParams',
'posts',
function($stateParams, posts) {
return posts.get($stateParams.id);
}
]
}
})
.state('login', {
url: '/login',
templateUrl: '/login.html',
controller: 'AuthCtrl',
onEnter: ['$state', 'auth', function($state, auth) {
if (auth.isLoggedIn()) {
$state.go('home');
}
}]
})
.state('register', {
url: '/register',
templateUrl: '/register.html',
controller: 'AuthCtrl',
onEnter: ['$state', 'auth', function($state, auth) {
if (auth.isLoggedIn()) {
$state.go('home');
}
}]
});
$urlRouterProvider.otherwise('/');
}
]);
fyi, the ".state('home', { url:" was ".state('home', { url: '/home'" but it show an error so I change it to "url: '/'" and the error was gone. But still the ui-view cannot display the templates.
This is the output:
enter image description here
Anyone has any idea on how to solve this? Does bower has anything to do with this?
You don't need the script tag once you have the template on the separate file. Remove it and it should works. You can just use the path of the file for the templateURL then
Sometimes you will something like this just like you have,
<script type="text/ng-template" id="template.html">
... some template stuff
</script>
That script tag was actually for having the template on the same file as the main template file, and you can use templateUrl with the value of the id attribute just like usual. It will treat the body of the script tag as a file of template.html since the value of the id is template.html
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.
I'm a newbie to Angular and working on a project but I'm having an issue with displaying info in two different pages.
I have a browse page that displays profiles
I also have a homepage where I want to display the contents of the browse page plus other miscellaneous information.
To do that I created a component(browsePage)
Then I added the component to the home.view.html
<browse-page></browse-page>
but the profiles don't show up.
In my browse page the profiles do show up.
My code:
app.config.js
$routeProvider
.when('/home', {
RouteData: {
bodyStyle: {
//'background': 'url(../images/bg-7.jpg)repeat'
'background-color': 'white'
}
},
controller: 'HomeController',
templateUrl: 'home/home.view.html',
controllerAs: 'vm'
})
.when('/browse', {
RouteData: {
bodyStyle: {
//'background': 'url(../images/bg-10.jpg)repeat'
'background-color': 'white'
}
},
controller: 'BrowseController',
templateUrl: 'browse/browse.view.html',
controllerAs: 'vm'
})
home.controller.js
angular.module("mango").controller("HomeController", HomeController);
function HomeController() {
}
angular.module('mango').controller('ExampleController', ['$cookies', function($cookies) {
}]);
home.view.html
This is the home page<br>
Miscellaneous info goes here
<browse-page></browse-page>
Miscellaneous info goes here<br>
end of home page
browse.component.js
console.log("In browse.component.js");
angular.module("mango").component("browsePage",{
templateUrl:"browse/browse.view.html",
controller:BrowseController
});
browse.controller.js
angular.module("mango").controller("BrowseController", BrowseController);
BrowseController.$inject = ["$rootScope","$location","AuthenticationService","$http"];
function BrowseController($rootScope, $location, AuthenticationService, $http){
var vm = this;
$http.get('browse_profiles.json').success(function(data){
vm.data = data;
console.log("data==>");
console.log(data);
});
}
browse.view.html
<br><br>
<!-- Page Content -->
<div class="container">
<!-- Jumbotron Header -->
<header class="jumbotron hero-spacer" >
<form ng-submit="submit()" ng-controller="ExampleController">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
</form>
</header>
<hr>
<!-- Page Features -->
<div class="row text-center">
<img id="mySpinner" src="/images/loader.gif" ng-show="loading" />
{{alpine}}
<div class="col-md-3 col-sm-6 hero-feature" ng-repeat="profile in vm.data">
<div class="thumbnail">
<img src="{{profile.thumbnail}}" alt="">
<div class="caption">
<div class="username-status">
<span class="username pull-left"><a ng-href="#/profile/{{profile.username}}">{{profile.username}}</a></span>
<p ng-class-odd="'circle odd'" ng-class-even="'circle even'"></p>
</div>
</div>
</div>
</div>
</div>
<!-- /.row -->
<hr>
<!-- Footer -->
<footer>
<div class="row">
<div class="col-lg-12">
<p>Copyright © Your Website 2014</p>
</div>
</div>
</footer>
</div>
End of browse view.
<br><br>
index.html
<!doctype html>
<html lang="en" ng-app="mango">
<head>
<meta charset="utf-8">
<title>Mango</title>
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="css/style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="bower_components/angular-resource/angular-resource.js"></script>
<script src="bower_components/angular-cookies/angular-cookies.js"></script>
<script src="app.config.js"></script>
<script src="login/route-data.js"></script>
<script src="navigation_menu/navigation_menu.config.js"></script>
<script src="browse/browse.controller.js"></script>
<script src="browse/browse.component.js"></script>
<script src="home/home.controller.js"></script>
<script src="profile/profile.controller.js"></script>
<script src="settings/settings.controller.js"></script>
<script src="login/login.controller.js"></script>
<script src="login/app-services/authentication.service.js"></script>
<script src="login/app-services/flash.service.js"></script>
<script src="login/app-services/user.service.local-storage.js"></script>
</head>
<body ng-style="RouteData.get('bodyStyle')" ng-cloak>
<navigationmenu ng-if="location.path() !== '/login'"></navigationmenu>
<ng-view autoscroll></ng-view>
</body>
</html>
I'm not getting any errors in the console.You can ignore the GET error.
What do I need to do to fix my problem?
I'm starting to think th
Thanks in advanced.
I think in your component, you haven't specified controllerAs, when you goto /browse, your browseView.html is getting the controller instance as vm, but when browseView.html is loaded through component,it is not getting the controller instance, as it is not getting instantiated like it is done, in routeProvider.
Try doing,
angular.module("mango").component("browsePage",{
templateUrl:"browse/browse.view.html",
controller:BrowseController,
controllerAs: 'vm'
});
Hope, this solves the issue.
I was following some random YT tutorial on using Angular's $routeProvider and the result - contrary to the video - is not working for me. Instead, what I get is crashed website and this error logged in Chrome's console: Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.4.8/$injector/modulerr?p0=site&p1=Error%3A%20…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.4.8%2Fangular.min.js%3A41%3A249) By following the trail, I found that there's something wrong with `$routeProvider', but beats me if I know what. Here's my code:
var site = angular.module('site', []).
config(function($routeProvider){
$routeProvider.
when('/home', {template:'/pages/home.html'}).
when('/', {template:'/pages/home.html'}).
when('/in-play', {template:'/pages/in-play.html'}).
when('/popular', {template:'/pages/popular.html'}).
otherwise({redirectTo:'/home', tempalte:'/pages/home.html'});
});
function MainCtrl($scope, $location) {
$scope.setRoute = function(route) {
$location.path(route);
};
};
And here are all the HTMLs (I'm working with ng-include also):
<!DOCTYPE html>
<html ng-app="site">
<head>
<link rel="stylesheet" href="css/style.css">
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="scripts/app.js"></script>
<title>Pre-Demo</title>
</head>
<body ng-controller="mainStaysCtrl">
<header class="header" ng-include="'pages/header.html'"></header>
<nav class="nav" ng-include="'pages/nav.html'"></nav>
<div class="main">
<div class="left-col">
<div class="quick links" ng-include="'pages/quick_links.html'"> </div>
<div class="quick-inplay links" ng-include="'pages/quick_inplay_links.html'"></div>
<div class="winner links" ng-include="'pages/winner_links.html'"></div>
</div>
<div class="center-col" ng-controller="mainCtrl">
<div class="wraper" ng-view ng-controller="jsonCtrl"></div>
</div>
<div class="right-col">
<div class="expert-mixer" ng-include="'pages/mixer.html'"></div>
<div ng-include="'pages/twitter.html'"></div>
</div>
</div>
</body>
</html>
//included page that has the call for $routeProvider
<div class="events">
<div class="bullet">
<div class="bullet-padding">
<div ng-click="setRoute('in-play')" class="bullet-link">In-Play Links</div>
</div>
</div>
</div>
Could someone please tell me what's wrong?
EDIT
After Antiga's answer I got it to load the page. Everything besides the content that is to be loaded with ng-view and for which $routeProvider was set up in the first place. Here's the updated code:
var site = angular.module('site', ['ngRoute']).
config(function($routeProvider){
$routeProvider.
when('/home', {templateUrl:'/pages/home.html'}).
when('/', {templateUrl:'/pages/home.html'}).
when('/in-play', {templateUrl:'/pages/in-play.html'}).
when('/popular', {templateUrl:'/pages/popular.html'}).
otherwise({redirectTo:'/home', tempalteUrl:'/pages/home.html'});
});
site.controller('mainStaysCtrl', function($scope) {
$scope.setRoute = function(route) {
$location.path(route);
};
});
and HTML
<body ng-controller="mainStaysCtrl">
<header class="header" ng-include="'pages/header.html'"></header>
<nav class="nav" ng-include="'pages/nav.html'"></nav>
<div class="main">
<div class="left-col">
<div class="quick links" ng-include="'pages/quick_links.html'"></div>
<div class="quick-inplay links" ng-include="'pages/quick_inplay_links.html'"></div>
<div class="winner links" ng-include="'pages/winner_links.html'"></div>
</div>
<div class="center-col">
<div class="wraper" ng-view ></div>
</div>
<div class="right-col">
<div class="expert-mixer" ng-include="'pages/mixer.html'"></div>
<div ng-include="'pages/twitter.html'"></div>
</div>
</div>
You are not including the routing module.
Read up on this here so that you actually understand it first: https://docs.angularjs.org/api/ngRoute
Add this after you include angular.min.js:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
And then include the dependency in your main app module:
var site = angular.module('site', ['ngRoute']).
Okay, I got it working beyond Antiga's help.
There was few (yet minor) problems. I had to extend templateUrl path to include project folder.
when('/home', {templateUrl: '/ProjectName/pages/home.html', controller: 'mainStaysCtrl'}).
Other thing is that I simply forgot to include $location in controller.
site.controller('mainStaysCtrl', function($scope, $location) {
$scope.setRoute = function(route) {
$location.path(route);
};
});