I'm working on a Angular route example but for some reason it's not working.
I've tried many pages and many things but doesn't seem to help.
Here's an
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="../Scripts/angular.min.js"></script>
<script src="../Scripts/angular-route.min.js"></script>
<script>
var app = angular.module("Main", ["ngRoute"]);
app.config(["$routeProvider", function ($routeProvider) {
$routeProvider.
when("/first", {
templateUrl: "_Pages/test.html",
controller: "first"
}).
when("/second", {
templateUrl: "_Pages/index.html",
controller: "second"
});
}]);
app.controller("first", function ($scope) {
$scope.list = [1, 2, 3, 4, 5];
});
app.controller("second", function ($scope) {
$scope.list = [1, 2, 3];
});
</script>
</head>
<body ng-app="Main">
<ul>
<li> first partial </li>
<li> second partial </li>
</ul>
<div ng-view></div>
</body>
</html>
Any advice would be pleasant!
it seems to be working fine. And Please check the angular version is compatible with the route. i create a sample Plunker
<script data-require="angular.js#1.5.10" data-semver="1.5.10" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.10/angular.min.js"></script>
<script data-require="angular-router#1.2.0-rc1" data-semver="1.2.0-rc1" src="https://code.angularjs.org/1.2.0rc1/angular-route.js"></script>
It's likely that there is a version issue in your angular js file inclusion.
Either you replace your file inclusion code by,
<script src="http://code.angularjs.org/1.4.8/angular.js"></script>
<script src="https://code.angularjs.org/1.2.16/angular-route.min.js"></script>
(or)
Copy the entire code from here. Here's the working version of angular JS & Route.
DEMO
Note : I changed templateUrl to template for demo purpose.
If you're using Angular 1.6, it's probably to do with the changes made to the default hash prefix. That is that as from v1.6.0 upwards ! is the default hash prefix, whereas it used to be "" (empty string).
To fix this issue, either...
Change your links as follows:
<li> first partial </li>
<li> second partial </li>
Or
Remove the hash prefix by injecting $locationProvider into the app.config and setting the hash prefix to the empty string as follows:
app.config(["$routeProvider", "$locationProvider", function ($routeProvider, $locationProvider) {
// with this the links can remain: href="#/first" and href="#/second"
$locationProvider.hashPrefix("");
$routeProvider.
when("/first", {
templateUrl: "_Pages/test.html",
controller: "first"
}).
when("/second", {
templateUrl: "_Pages/index.html",
controller: "second"
});
}]);
Further Reading:
Angular Issues - Angular 1.6.0 incorrectly redirects to hashbang
Angular Docs - Migrating from v1.5 to 1.6
Related
I'm teaching myself AngularJS by trying to make a simple app. I'm having some trouble with data binding when using a controller.
todo-item.js
'use strict';
angular.module('todoItem', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/todoItem', {
templateUrl: 'todo-item/todo-item.template.html',
controller: 'TodoItemCtrl'
});
}])
.controller('TodoItemCtrl', [function() {
this.test = [1, 2, 3, 4];
}]);
todo-item.template.html
<p>This is the partial for todo item.</p>
<p>
this is just a test
</p>
<p>{{$ctrl.test}}</p>
<ul>
<li ng-repeat="i in $ctrl.test">{{i}}</li>
</ul>
What I am seeing is the web-page display:
This is the partial for todo item.
this is just a test
So this indicates the template is rendering, however without the data binding dependent part...
If I put a console.log(this.test) in the controller code just after the line this.test = [1, 2, 3, 4], it does print the array object to the console Array(4) [ 1, 2, 3, 4 ]. So I know the controller code must be running...
What am I missing?
Also being new to AngularJS, I'm not familiar with debugging in this framework yet. How would you normally debug something like this? Can I goto the console and do something like >>$ctrl?
In case it helps here is app.js
'use strict';
// Declare app level module which depends on views, and core components
angular.module('todoApp', [
'ngRoute',
'todoList',
'todoItem'
]).
config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
$locationProvider.hashPrefix('!');
$routeProvider.otherwise({redirectTo: '/todoList'});
}]);
and index.html:
<!DOCTYPE html>
<html lang="en" ng-app="todoApp">
<head>
<meta charset="utf-8">
<title>ToDo AngularJS App</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="app.css">
</head>
<body>
<div ng-view></div>
<script src="lib/angular/angular.js"></script>
<script src="lib/angular-route/angular-route.js"></script>
<script src="app.js"></script>
<script src="todo-list/todo-list.js"></script>
<script src="todo-item/todo-item.js"></script>
</body>
</html>
I think you might need to provide controllerAs: '$ctrl' in your route provider, so
$routeProvider.when('/todoItem', {
templateUrl: 'todo-item/todo-item.template.html',
controller: 'TodoItemCtrl',
controllerAs: '$ctrl'
});
To answer the question while avoiding $scope and instead using something more isolated as the AngularJS docs suggest, components is the way to go.
To achieve this I changed app.js to handle the routes and crucially use components:
'use strict';
// Declare app level module which depends on views, and core components
angular.module('todoApp', [
'ngRoute',
'todoList',
'todoItem'
])
.config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
$locationProvider.hashPrefix('!');
$routeProvider.
when('/todoList', {
template: '<todo-list></todo-list>'
})
.when('/todoItem', {
template: '<todo-item></todo-item>'
})
.otherwise({redirectTo: '/todoList'});
}]);
Then I implemented the component in todo-item.js:
'use strict';
angular.module('todoItem', ['ngRoute'])
.component('todoItem', {
templateUrl: 'todo-item/todo-item.template.html',
controller: 'TodoItemCtrl'
})
.controller('TodoItemCtrl', [function() {
this.test = [1, 2, 3, 4];
}]);
To use $scope see Anurag Srivastava answer. I'm not sure what's the best way, as I have much to learn.
I just created a simple project to learn angular routing, my project is the following:
index.html:
<!DOCTYPE html>
<html ng-app="app">
<body>
<div>
Home
Hi
bye
</div>
<div class="ng-view"></div>
<script src="https://code.angularjs.org/1.6.3/angular.min.js"></script>
<script src="https://code.angularjs.org/1.6.3/angular-route.min.js"></script>
<script src="scripts.js"></script>
</body>
</html>
scripts.js:
var app = angular.module("app", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "home.html"
})
.when("/hi", {
templateUrl: "hi.html"
})
.when("/bye", {
templateUrl: "bye.html"
});
});
hi.html: <h1>Hi</h1>
bye.html: <h1>bye</h1>
home.html: <h1>Home</h1>
The three html from above only contains a h1 tag to keep it simple
A plunker of my code: http://plnkr.co/edit/uNZicTuRKDkR7ATwdFE0
I'm following this tutorial: https://www.w3schools.com/angular/angular_routing.asp
Dunno if outdated or why its not working, thanks
The problem is that you are using angular 1.6 and the toturial is using 1.4. Your links should be like this because of the new hash prefix in version 1.6:
<div>
<a ng-href="#!/">Home</a>
<a ng-href="#!/hi">Hi</a>
<a ng-href="#!/bye">bye</a>
</div>
See plunker.
http://plnkr.co/edit/qUYYcFjfwi9kEGxa7zOu?p=preview
Read more about what else to do at: https://stackoverflow.com/a/41655831/6682369
I'm trying to build a simple AngularApp Here. I'm trying to add routeProvider and use config for the same. But the page never worked as expected. When I tried using fireBug in firefox, I found that the function present in the config, was never invoked. So, the code inside it remains untouched. (I was able to confirm that with breakpoints).
I believe that I'm missing something trivial here. Please help me figure it out.
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular-route.min.js" type="text/javascript"></script>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/navbar.js"></script>
<script type="text/javascript" src="js/kscApp.js"></script>
</head>
<body>
<div ng-app="navbar">
<nav-bar></nav-bar>
</div>
<div ng-app="kscapp">
<ul>
<li> Home </li>
<li> Contact </li>
</ul>
<div ng-view></div>
</div>
</body>
</html>
kscapp.js
//Define an angular module for our app
var sampleApp = angular.module('kscapp',[]);
//Define Routing for app
//STACKOVERFLOW: The function is not getting invoked here. Please feel free to use firebug to verify the same.
sampleApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'templates/home.html',
controller: 'HomeCtrl'
}).
when('/Contact', {
templateUrl: 'templates/contact.html',
controller: 'ContactCtrl'
}).
otherwise({
redirectTo: '/home'
});
}]);
sampleApp.controller('HomeCtrl', function($scope) {
console.log('inside Hc');
});
sampleApp.controller('ContactCtrl', function($scope) {
console.log('inside Cc');
});
navbar.js
var navBarModule = angular.module('navbar', []);
navBarModule.directive('navBar', function() {
return {
scope: {},
templateUrl: 'templates/navbar.html'
};
});
EDIT: I had two ng-app in the source. I removed the navBar, and now things start to work fine. Can someone explain to me why this behaviour is seen? Both modules are independent of each other.
You don't inject the ng route module.It should be
var sampleApp = angular.module('kscapp',['ngRoute']);
You are using different versions for Angular.min.js and Angular-route.min.js.
update your angular-route from 1.2.9 to 1.3.8
Also inject 'ngRoute' to kscapp module.
You can only use 'ng-app' once in your application.
Concider moving your ng-app="kscapp" up to the html tag, and update kscapp to:
var sampleApp = angular.module('kscapp',['ngRoute', 'navbar']);
For more on ngApp, read ngApp API.
ngRoute not working while no errors are reported to console .
given no errors to console, how is it possible to follow execution of ngRoute procedures ?
i saw examples using $locationProvider.html5Mode(true), i don't understand when that should be used but i don't think it is required to make ngRoute work.
index.html has navigation links and ngView :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="bower_components/angular/angular.js"> </script>
<script src="bower_components/angular-route/angular-route.js"> </script>
<script src="main.js"> </script>
</head>
<body ng-app="Main">
<ul>
<li> first partial </li>
<li> second partial </li>
</ul>
<div ng-view></div>
</body>
</html>
main.js defines the router and the controllers :
var Main = angular.module('Main', ['ngRoute']);
function router($routeProvider) {
var route = {templateUrl: 'partials/default.html'};
$routeProvider.when('', route);
route = {
templateUrl: 'partials/first.html',
controller: 'first'
};
$routeProvider.when('content/first', route);
route = {
templateUrl: 'partials/second.html',
controller: 'second'
};
$routeProvider.when('content/second', route);
}
Main.config(['$routeProvider', router]);
Main.controller('first', function($scope) {
$scope.list = [1,2,3,4,5];
});
Main.controller('second', function($scope) {
$scope.list = [1,2,3];
});
partials simply make use of ngRepeat:
<header> First content </header>
<p ng-repeat="iter in list">
first
</p>
solved :
my problem was that my whole application is located under /ang/ prefix, and after adding that prefix to urls now it is working .
shouldn't there be a way to use relative urls ? i guess there should and i will try to fix it .
the problem is NOT with the different syntax as everyone suggested, and that is alarming to the fact many JS developer do not in fact understand the one line syntax that they are using everywhere .
Please check this code
HTML code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular-route.js"> </script>
<script src="script.js"> </script>
</head>
<body ng-app="Main">
<ul>
<li> first partial </li>
<li> second partial </li>
</ul>
<div ng-view></div>
</body>
</html>
Js file
var app = angular.module('Main', ['ngRoute']);
app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider.
when('/content/first', {
templateUrl: 'first.html',
controller: 'first'
}).
when('/content/second', {
templateUrl: 'second.html',
controller: 'second'
});
}]);
app.controller('first', function($scope) {
$scope.list = [1,2,3,4,5];
});
app.controller('second', function($scope) {
$scope.list = [1,2,3];
});
first page HTML
<header> First content </header>
<p ng-repeat="item in list">
{{item}}
</p>
here is your working code click
Do not reuse the route object as it might cause problems. Consider using it in the form (as suggested by the docs https://docs.angularjs.org/api/ngRoute/service/$route#example ):
$routeProvider
.when('content/second', {
templateUrl: 'partials/second.html',
controller: 'second'
});
If you want to debug the routes that angular goes through, you might want to look at angular's interceptors: https://docs.angularjs.org/api/ng/service/$http#interceptors
Also, $locationProvider.html5Mode(true) is not needed to make ngRoute work. It is simply a way of defining how the URLs should look like and work. in HTML mode you can change the links to not use # anymore and simply be www.yoursite.com/app/content/second instead of www.yoursite.com/app#content/second
your route configuration is not correct, you assume route function is execute for each and every link u click but its not.
so your route function should be like
function router($routeProvider) {
$routeProvider.
when('/content/first', {
templateUrl: 'partials/first.html',
controller: 'first'
}).
when('/content/second', {
templateUrl: 'partials/second.html',
controller: 'second'
}).
otherwise({
templateUrl: 'partials/default.html'
});
}
note that urls should be like <a href="#/content/first"> // note the slash after #
to match that the routes in route function should be like when('/content/first', { note the leading slash
here is the working Plunker
Define your Routes in routes.js
var route = angular.module('route', ['ngRoute']);
route.config(function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "views/home.html",
controller : 'homeCtrl'
})
.when("/home", {
templateUrl: "views/home.html",
controller : 'homeCtrl'
})
.when("/product", {
templateUrl: "views/product-info.html"
})
.otherwise({redirectTo :'/'});
});
Attach the router to your Main Module.
angular.module('myApp', ['route']);
Import both the scripts in your index.html
Everything worked fine until I tried to add routing. I read that Angularjs version 1.2+ requires 'ngRoute' as an dependency (I am using version 1.2.16). I added it but it still doesn't work. Below are my codes.
test.html (Main Page)
<html ng-app="demoApp">
<head>
<title></title>
</head>
<body>
<p>Front Page</p>
<div ng-view></div>
<script src="angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-route.js"></script>
<script src="testjs.js"></script>
</body>
</html>
testjs.js
demoApp = angular.module('demoApp',['ngRoute']);
demoApp.config(function ($routeProvider) {
$routeProvider.when('/', {
controller: 'SimpleController',
templateUrl: '/partials/first.html'
});
});
var controllers = {};
controllers.SimpleController = function ($scope){
$scope.first = "Info";
$scope.customers=[
{name:'jerry',city:'chicago'},
{name:'tom',city:'houston'},
{name:'enslo',city:'taipei'}
];
};
demoApp.controller(controllers);
first.html
<div>
<input type="text" ng-model="name"/>
</br>
{{first}}
</br>
<ul>
<li ng-repeat="cust in customers | filter:name">{{cust.name | uppercase}} - {{cust.city}}</li>
</ul>
</div>
Here is the most basic setup possble, I'll try to make another one with your code:
http://plnkr.co/edit/sN9TagVBOdX3mkrxaTiu?p=preview
EDIT updated with the sample code. Everything seems to be working?
EDIT 2 the problem is OP wasn't running a webserver. Ng-Route needs a webserver to function properly.
My routing wasn't working because there was an exclamation point inserted in the url when I tried to navigate to my routes. I added $locationProvider like this
app.config(function($routeProvider, $locationProvider) {
$locationProvider.hashPrefix('');
to remove the exclamation point and my template views started appearing when I navigated to them. I found the answer here Exclamation mark after hash (#!) in angularjs app