how to add routing in angularjs app? - angularjs

I am new to angularjs ,i make a sample app with custom directives now i add routing as well but it doesn't working.When i start project index file is loaded in browser that is working fine but when i click on nav bar links then about and contact page is not displayed it's remains on index.html.
here is my index.html:
<html ng-app="myApp">
<head>
<title>Reddit New World News (Task)</title>
<link href='http://fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
<script src="angular/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular-route.min.js"></script>
<script src="myApp.js"></script>
<script src="myAppCtrl.js"></script>
<script src="headerDirective.js"></script>
<script src="searchDirective.js"></script>
<script src="myDataDirective.js"></script>
<!-- start menu -->
</head>
<body>
<div header-table></div>
<div class="content" ng-controller = "myAppCtrl">
<div class="container" >
<div ng-view></div>
</div>
</div>
</body>
</html>
myAppCtrl:
// TODO: Wrap in anonymous function
(function () {
var myApp = angular.module('myApp', ['ngRoute']);
// configure our routes
myApp.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'code/index.html',
controller : 'myAppCtrl'
})
// route for the about page
.when('/about', {
templateUrl : 'code/about.html',
controller : 'aboutController'
})
// route for the contact page
.when('/contact', {
templateUrl : 'code/contact.html',
controller : 'contactController'
});
});
// TODO: min-safe with bracket notation
myApp.controller('myAppCtrl', ['$scope', '$http', function($scope, $http) {
$scope.sortType = '';
$scope.sortReverse = true;
// TODO: Keep lines short - it's easier to read
$http.get("https://www.reddit.com/r/worldnews/new.json")
.success(function (response) {
$scope.stories = response.data.children;
});
}]);
myAppCtrl.controller('aboutController',function(){
// create a message to display in our view
$scope.message = 'Everyone come and see how good I look!';
});
myAppCtrl.controller('contactController', function($scope) {
$scope.message = 'Contact us! JK. This is just a demo.';
});
})();
headerDirective.html:
<div class="top-header"></div>
<div class="container">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="header">
<h1>Reddit</h1>
</div>
<div class="header-right">
<h2>World's Latest News</h2>
</div>
<div>
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
</div>
</nav>
<div class="clearfix"></div>
</div>
any guide thanks.

Like some people allready mentioned, you should deffinitly read the docs and probably watch some tutorials. I'm trying to see what you are doing, but it's not clear to me.
But I think I see where it goes wrong in your thoughts:
You have 3 'templates' index.html, about.html and contact.html. In your config You use them in your routing. By watching your files my guess is that you are expecting that, depending on the route, these html-files will be loaded. Just like when redirecting to that page.
What you should do is make a index.html with the html You use on every page. this can be the <head></head> only, but can also contain your header with navigation and footer. Then you use <ng-view></ng-view> or <div ng-view></div> where you want the templates to load in your page. These templates don't need to contain the parts you allready defined in your index.html. You have only the content in it.
So, a simple example:
index.html
<html>
<head>
//loading your scripts etc.
</head>
<body>
<ng-view></ng-view>
</body>
</html>
Than, instead of creating a template called index.html, you make a template home.html with the content:
<div class="container">
<h1>My Home</h1>
</div>
Now the contentpart from your home.html will load in your index.html where you define de ng-view.
An other thing I noticed is the path you define in templateUrl. You define the location as code/about.html. You have to give it the path from your index.html (the main html) In your case that will just be templateUrl: 'about.html'.
I would suggest putting the different files in different folders. So, one for your templates, one for your js-files (probably a js-folder with another folder in it for your js-file with directives etc.).
I hope this will help you on your way. But deffinitly read the docs and watch some tutorials. It will help you a lot.

Related

AngularJS Route does not loading view

My project structure is looks like this:
I tried to make a single page application using this image. When index.html page will launch it will by default load registration.html in ng-view. But when index.html loads it does not load the registration.html as ng-view as expected.
And my files for index.html,main.css and mainAppRouter.js are below:
//mainAppRouter.js
(function () {
var myModule = angular.module('studentInfo', ['ngRoute']);
myModule.config(function ($routeProvider) {
$routeProvider
.when('/registration', {
templateUrl : '../views/registration.html',
controller: 'regController'
})
.otherwise({
redirectTo: '/registration'
});
console.log("checking");
});
myModule.controller('regController', function ($scope) {
$scope.message = 'This is Add new order screen';
console.log("checking");
});
});
/*man.css*/
.studentInfo{
margin-top: 100px;
}
.navbar{
padding: 1em;
}
.navbar-brand {
padding:0;
}
<!--index.html-->
<!DOCTYPE html>
<html data-ng-app="studentInfo">
<head>
<script src="lib/js/angular.min.js"></script>
<script src="lib/js/jquery-3.0.0.min.js"></script>
<script src="lib/js/bootstrap.min.js"></script>
<script type="text/javascript" src="lib/js/angular-route.js"></script>
<script src="app/route/mainAppRouter.js"></script>
<link rel="stylesheet" href="lib/css/bootstrap.css" />
<link rel="stylesheet" href="lib/css/bootstrap-theme.css" />
<link rel="stylesheet" href="app/css/main.css" />
<title>A demo Angular JS app</title>
</head>
<body>
<div class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#"> <span><img src="app/images/people.png"/></span> Student Info </a>
</div>
<ul class="nav nav-pills navbar-right" data-ng-controller="NavbarController">
<li role="presentation">Registration</li>
<li role="presentation">Student Details</li>
</ul>
</div>
</div>
<div class="container">
<div class="col-md-4 col-md-offset-4" data-ng-controller="regController">
<h1>Student Info</h1>
</div>
<div ng-view></div>
</div>
</body>
</html>
All my codes are in this github repo
What should i do to correct my problem?
I think the problem is because you have not specified any controller for your ng-view and also you have to set your base URL correctly.
$routeProvider
.when('/registration', {
templateUrl :'http://localhost/StudentInfo/app/views/registration.html',
controller: 'regController'
})
And remove the controller tag from HTML.Your controller tag was outside the scope of ng-view.
<div class="container">
<div class="col-md-4 col-md-offset-4" >
<h1>Student Info</h1>
</div>
<div ng-view></div>
</div>
And there is a syntax error in your controller as well
myModule.controller('regController', function ($scope){
$scope.message = 'This is Add new order screen';
})
UPDATED ANSWER: Another reason why this does not work is that you are running your example off the file system (using the file:// protocol) and many browsers (Chrome, Opera) restricts XHR calls when using the file:// protocol. AngularJS templates are downloaded via XHR and this, combined with the usage of the file:// protocol results in the error you are getting.
For more details: Couldn't load template using templateUrl in Angularjs

Removing the # from AngularJS Routing

I checked Single Page Apps with AngularJS Routing and Templating tutorial
and found Pretty URLs in AngularJS: Removing the # tutorial for remove # tag from URL. I did all the things but I can't get the app working. It would be great help someone can help on this. These are my codes,
// script.js
// create the module and name it scotchApp
// also include ngRoute for all our routing needs
var scotchApp = angular.module('scotchApp', ['ngRoute']);
// configure our routes
scotchApp.config(function($routeProvider, $locationProvider) {
$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'
});
// use the HTML5 History API
$locationProvider.html5Mode(true);
});
// create the controller and inject Angular's $scope
scotchApp.controller('mainController', function($scope) {
// create a message to display in our view
$scope.message = 'Everyone come and see how good I look!';
});
scotchApp.controller('aboutController', function($scope) {
$scope.message = 'Look! I am an about page.';
});
scotchApp.controller('contactController', function($scope) {
$scope.message = 'Contact us! JK. This is just a demo.';
});
<!-- index.html -->
<!DOCTYPE html>
<!-- define angular app -->
<html ng-app="scotchApp">
<head>
<base href="/">
<!-- SCROLLS -->
<!-- load bootstrap and fontawesome via CDN -->
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" />
<!-- SPELLS -->
<!-- load angular via CDN -->
<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.25/angular-route.js"></script>
<script src="script.js"></script>
</head>
<!-- define angular controller -->
<body ng-controller="mainController">
<!-- HEADER AND NAVBAR -->
<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">
<!-- angular templating -->
<!-- this is where content will be injected -->
<div ng-view></div>
</div>
</body>
</html>
After the first tutorial my URL become
file:///C:/Users/MAX/Desktop/angular/AngularJS%20Routing/index.html#/
but after Second one URL becomes
file:///C:/Users/MAX/Desktop/angular/AngularJS%20Routing/index.html#%2F
and links stop woking
It's easy to solve.
You just need to inject ($locationProvider) where you declare your module and put this code ($locationProvider.html5Mode(true)) inside the function.
Something like this.
var myApp = angular.module('myApp',[]);
myApp.config(function ($locationProvider){
$locationProvider.html5Mode(true);
});
You must not directly open angular's html files in your browser. You should rather start a simple http server for the same. The easiest way to do so,
Assuming you have Python 2.7 installed on your filesystem:
python -m http.server <portNo>
for serving the directory contents to http://localhost:<portNo>/
Then you also will be able to navigate to http://localhost:<portNo>/about and http://localhost:<portNo>/contact
Example:
Navigating to your project's main directory and then running python -m http.server 8888 would serve files to http://localhost:8888/ , where the routing should work correctly.
First, remove the hashmark from your <a href="#...">s, like <a href="about"> or <a href="/about">. I also suggest you to use ng-href instead of href
Second, use some local http server, like python -m http.server to serve your files.
Note: If you wisht to use html5 mode, and want your app to work well when the user does not land on index.html, but on another route, you must configure the http server to serve index.html on all of your routes. We do it usually by serving index.html directly instead of returning 404.
Finally with the help of above answers I figured to find an answer. (I used wamp server as local web server)
My sile structure
angulRoute
- script.js
- index.html
- pages
----- home.html
----- about.html
----- contact.html
// script.js
// create the module and name it scotchApp
// also include ngRoute for all our routing needs
var scotchApp = angular.module('scotchApp', ['ngRoute']);
// configure our routes
scotchApp.config(function($routeProvider, $locationProvider) {
$routeProvider
// route for the home page
.when('/angulRoute/', {
templateUrl: 'pages/home.html',
controller: 'mainController'
})
// route for the about page
.when('/angulRoute/about', {
templateUrl: 'pages/about.html',
controller: 'aboutController'
})
// route for the contact page
.when('/angulRoute/contact', {
templateUrl: 'pages/contact.html',
controller: 'contactController'
});
// use the HTML5 History API
$locationProvider.html5Mode(true);
});
// create the controller and inject Angular's $scope
scotchApp.controller('mainController', function($scope) {
// create a message to display in our view
$scope.message = 'Everyone come and see how good I look!';
});
scotchApp.controller('aboutController', function($scope) {
$scope.message = 'Look! I am an about page.';
});
scotchApp.controller('contactController', function($scope) {
$scope.message = 'Contact us! JK. This is just a demo.';
});
<!-- index.html -->
<!DOCTYPE html>
<html ng-app="scotchApp">
<head>
<meta charset="utf-8">
<!-- SCROLLS -->
<!-- load bootstrap and fontawesome via CDN -->
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" />
<!-- SPELLS -->
<!-- load angular and angular route via CDN -->
<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.25/angular-route.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="mainController">
<!-- HEADER AND NAVBAR -->
<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><a ng-href="/angulRoute/"><i class="fa fa-home"></i> Home</a></li>
<li><a ng-href="/angulRoute/about"><i class="fa fa-shield"></i> About</a></li>
<li><a ng-href="/angulRoute/contact"><i class="fa fa-comment"></i> Contact</a></li>
</ul>
</div>
</nav>
</header>
<!-- MAIN CONTENT AND INJECTED VIEWS -->
<div id="main">
<!-- angular templating -->
<!-- this is where content will be injected -->
<div ng-view></div>
</div>
</body>
</html>

The pages not loading in ng view by Routers

<head>
<script src=jquery.js></script>
<script src=bootstrap.js></script>
<script src=angular.js></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
<link rel=stylesheet type="text/css" href=bootstrap.css />
<link rel=stylesheet type=text/css href=mystyle.css />
<style>
#panel{margin:20px;}
#addNew{margin:10px;}
#pagination{text-align:center;}
span{background:#aaa;width:60px;width:60px;}
</style>
</head>
<body ng-app="myApp">
<div ng-controller=myController>
<div id=panel class="panel panel-primary">
<div class="panel-heading">Hero Selection Bar</div>
<div class="panel-body">
Page 1
Page 2
Page 3
<ng-view > </ng-view>
</div>
</div>
</div>
<script>
var app = angular.module('myApp',['ngRoute']);
app.controller('myController', function( $scope, $routeProvider){
$scope.somedata = "THAT";
});
app.config([$routeProvider],function($routeProvider){
$routeProvider
.when('#/one', {templateUrl:"templates/one.html"})
.when('#/two', {templateUrl:"templates/two.html"})
.when('#/three', {templateUrl:"templates/three.html"})
});
</script>
</body>
I have kept the files on templates/one.html, templates/two.html, and templates/three.html in 'templates folder' but I am unable to get the pages load in current angularjs page. Can someone help me out in getting the routes load the required pages.
There are couple of things your are doing wrong:-
1)# in when not required it should be like .when('/one', {templateUrl:"templates/one.html"}) etc.
2)Array notation must be end at the end ['$routeProvider'] not correct
It should be like :-
app.config(['$routeProvider',function($routeProvider){
$routeProvider
.when('/one', {templateUrl:"one.html"})
.when('/two', {templateUrl:"two.html"})
.when('/three', {templateUrl:"three.html"}).otherwise({redirectTo:'/one'})
}]);
3)$routeProvider not required in controller use $route.
4) I guess use otherwise it also required (It is optional).
Plunker
You added [$routeProvider] which has ] which should be closing bracket of dependency.
Config
app.config([$routeProvider,function($routeProvider){
$routeProvider
.when('/one', {templateUrl:"templates/one.html"})
.when('/two', {templateUrl:"templates/two.html"})
.when('/three', {templateUrl:"templates/three.html"})
}]);
Inside controller you can not inject $routeProvider dependency it should $route

angularJS $routeProvider

I am using angularJS in my grails application. Before that, i tried a sample from internet. I tried to use angularJS $routeProvider for the partial views in my main view. My workflows are as follows:
my main view is index.gsp:
<!DOCTYPE html>
<html lang="en">
<head>
<title>AngularJS Routing example</title>
</head>
<body ng-app="routeApplication">
<div class="container">
<div class="row">
<div class="col-md-3">
<ul class="nav">
<li> Add </li>
<li> Show </li>
</ul>
</div>
<div class="col-md-9">
<div ng-view></div>
</div>
</div>
</div>
<script src="js/angular.js"></script>
<script src="js/angular-route.js"></script>
<script src="js/app.js"></script>
</body>
</html>
My partial views are: add_order.gsp and show_orders.gsp to show a sample message for each view.
my app.js is as follows:
var sampleApp = angular.module('routeApplication', ['ngRoute']);
sampleApp.config(['$routeProvider',
function($routeProvider) {
var base = '${request.contextPath}';
$routeProvider.
when('/AddNewOrder', {
templateUrl: 'templates/add_order.html',
controller: 'AddOrderController'
}).
when('/ShowOrders', {
templateUrl: 'templates/show_orders.gsp',
controller: 'ShowOrdersController'
}).
otherwise({
redirectTo: '/AddNewOrder'
});
}]);
sampleApp.controller('AddOrderController', function($scope) {
$scope.message = 'This is Add new order screen';
});
sampleApp.controller('ShowOrdersController', function($scope) {
$scope.message = 'This is Show orders screen';
});
Note: i created a templates folder and placed my parital views on that.
This problem is that, whenever i click to load my partial views it shows
`http://localhost/angularJSrouting/templates/show_orders.gsp`
404 Not Found
Am i missing something or is there any problem of placing the partial views?
I don't think this will work. Since your templateUrl is templates/show_orders.gsp angularjs will try to find that file inside templates folder in your webapp.
You have to redirect to
http://localhost/#/angularJSrouting/templates/show_orders.gsp url
can you use '/' instead of '#' in those html line
<li> Add </li>
<li> Show </li>

need advice on ng-view layout please

I am designing a page in angularjs that would be a mini SPA (single page app). This page is part of a larger web site that was written in traditional jquery and asp.net. The page will have 2 main sections - the 1st section is just some simple data elements that can be bound easily with ng-model's. The 2nd section will be dynamically generated based on user's interaction, and the data will be retrieved through ajax ($http or $resource).
So should I have ng-view on the whole content page that contains the 2 sections? Or should I only do ng-view on the 2nd dynamic sections? If it's better to have ng-view on the 2nd section only, how do I handle the routes in this case knowing that the 1st section's data should be preserved statically?
thanks.
You don't have to use ng-view and routes for your simple case (widget-like angular application inside other application). You can use ng-include instead. Here is an example of application. I prefer this approach because it does not require to use shared resource like URL location hash that may be already in a use by legacy application or other widgets. Application below switch views dynamically, loads different data for each view and affects it's display options (number of displayed items):
HTML
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#*" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script data-require="angular.js#*" data-semver="1.2.11" src="http://code.angularjs.org/1.2.11/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<h1>Here is my legacy app markup</h1>
<div ng-app="app" ng-controller="appController">
<div>
<input placeholder="Number of items" ng-model="numberOfItems"/><br/>
<select placeholder="View" ng-model="currentView" ng-options="view.name for view in views"></select>
</div>
<div ng-include="currentView.url"></div>
</div>
<div id="jqueryContainer">And here is some markup generated with jQuery<br /></div>
</body>
</html>
JavaScript
angular.module('app', []).
controller('appController', function($scope, $http) {
$scope.views = [{
name: 'view1',
url: 'view1.html',
dataUrl: 'data1.json'
}, {
name: 'view2',
url: 'view2.html',
dataUrl: 'data2.json'
}];
$scope.numberOfItems = 2;
$scope.currentView = $scope.views[0];
$scope.$watch('currentView', function(currentView) {
if(currentView && currentView.dataUrl) {
$http.get(currentView.dataUrl).success(function(data) {
$scope.data = data;
});
}
});
});
$(function(){
$('#jqueryContainer').append('<span>Some markup generated dynamically.</span>');
});
view1.html
<div>
<h2>View1 specific markup {{data.length}}</h2>
<ul>
<li ng-repeat="item in data | limitTo:numberOfItems">{{item.text}}</li>
</ul>
</div>
data1.json
[{"text":"Text1"},{"text":"Text2"},{"text":"Text3"},{"text":"Text4"},{"text":"Text5"}]
Plunker: http://plnkr.co/edit/Y5IZmPbrrO63YrL8uCkc?p=preview
You can also find useful examples of this approach in AngularJS documentation: http://docs.angularjs.org/api/ng.directive:ngInclude
yes you can separate the static view with the dynamic view, in actual this is what angularjs suggest.It is not required to move the scope of ng-app.
so you can do like this: menu is displayed as the static part
index.html
<body ng-app>
<ul class="menu">
<li>view1</li>
<li>view2</li>
</ul>
<div ng-view></div>
</body>
in your config file you can include your routing which page routes to which page and which controller to used on loading of any view.
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl1'});
$routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});

Resources