I'm trying to configure routes in Angular. Here's what I have:
<!DOCTYPE html>
<html ng-app="countryApp">
<head>
<meta charset="utf-8">
<title>Angular.js-add routes</title>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular-route.min.js"></script>
<script>
var countryApp = angular.module('countryApp', ['ngRoute']);
countryApp.config(function($routeProvider){
$routeProvider.
when('/',{
template: '<ul><li ng-repeat="country in countries">{{country.countryName}}</li></ul>',
controller: 'CountryListCtrl'
}).
when('/:countryName',{
template: '<h1>TODO create country detail view</h1>',
controller: 'CountryDetailCtrl'
}).
otherwise({
redirectTo:'/'
});
});
countryApp.controller('countryListCtrl', function($scope,$http){
$http.get('countries.php').success(function(data){
$scope.countries=data;
});
});
countryApp.controller('countryDetailCtrl', function($scope,$routeParams){
console.log($routeParams);
});
</script>
</head>
<body ng-controller= "countryListCtrl">
<ul>
<li ng-repeat="country in countries">{{country.countryName}}</li>
</ul>
</body>
</html>
The code above is saved in a ng-app.html file.
My Question:
ng-app.html -works
ng-app.html/ - does not work. Gives “Access to restricted URI denied.....” error
ng-app.html/USA - does not work. Gives File Not Found Error Page
When I try running the above file on a server (localhost), I get a file not found error page for both of the above "does not work" cases.
Thanks #charlietfl .
The url indeed ends up being: ng-app.html#/USA
I also wanted to point out that I a made few typos. The controllers countryListCtrl and countryDetailCtrl both start with lower case c's in the definition. But I have used uppercase C's in the routing part.
Related
I have my app.js and controller.js files stored in a js folder for the project, here's a snippet of each
app.js
var myApp = angular.module('myApp', ['ngRoute','RouteControllers']);
myApp.config(["$routeProvider",function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: 'templates/home.html',
controller: 'HomeController'
}).
when("/about", {
templateUrl: 'templates/biography.html',
controller: 'BiographyController'
});
}]);
controller.js
angular.module('RouteControllers', [])
.controller('HomeController', function($scope) {
$scope.title = "Welcome to Website!"
console.log("HomeController: I was instantiated!")
})
.controller('BiographyController', function($scope) {
$scope.title = "About"
});
Then I have my index.html file, the basics:
<base href="/">
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css" />
<link rel="stylesheet" href="css/style.css">
<body ng-app="myApp">
Home
About
<div ng-view> </div>
<script src ="bower_components/angular/angular.min.js"></script>
<script src="bower_components/angular-route/angular-route.min.js"></script>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controller.js"></script>
</html>
My issue is that the text from the home page is shown when I load the page (as it should) but then when I click on about I get the following come up instead:
'Page Not Found
This specified file was not found on this website. Please check the URL for mistakes and try again.
Why am I seeing this?
This page was generated by the Firebase Command-Line Interface. To modify it, edit the 404.html file in your project's configured public directory.'
The error in the console is simply 'Failed to load resource: the server responded with a status of 404 ()'
I have been searching for what the issue is but can't find one, the url when I click on about is 'http://localhost:5000/about'.
You will need to add the # to your anchors
Home
About
this will make it works. Also, you have the option to do it programmatically using the $location service
.controller('HomeController', ['$scope', '$location', function($scope, $location) {
$scope.title = "Welcome to Website!";
console.log("HomeController: I was instantiated!");
$scope.goAbout = function() {
$location.path('/about');
};
}])
Now you can use the goAbout funtion in your template
<div>
<h1>{{title}}</h1>
<button ng-click="goAbout()">About us</button>
</div>
But, if you want to take advantage of the HTML5 mode, get rid of the # and have prettier url , at least in the browsers that support the HTML5 mode, then you need some updates in your code
myApp.config(["$routeProvider", '$locationProvider',
function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
......
Inject the $locationProvider service and set $locationProvider.html5Mode(true);
If you don't need the <base href="/"> tag, then use an object like this
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
Now, your links need to change
Home
About
And you will have prettier urls. Please, notice that HTML5 mode may need some server side configuration in order to redirect all the navigation to your index page
Hope it helps
I'm new to angular and am having a hard time getting ngRoute to pick up my template file.
Here is my index.html:
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular-route.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular-animate.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="app.js"></script>
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">
<link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/main.css" />
</head>
<nav>
<div>
<ul>
<li>home</li>
</ul>
</div>
</nav>
<body>
<div ng-view>
</div>
</body>
</html>
Here is my app.js:
var myApp = angular.module('myApp', ['ngRoute']);
myApp.controller('MainCtrl', function($scope) {
$scope.message = 'Hello World';
});
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'pages/home.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/home'
});
}]);
Here is my pages/home.html:
<div ng-controller="MainCtrl">
<p>Test</p>
<p>{{ message }}</p>
</div>
I can see that it is appending #/ to the root url so perhaps this is partially working; however, it doesn't seem to be rendering the template at "pages/home.html".
I've checked the cdn url's to make sure there wasn't any version inconsistencies, and what not, but that doesn't seem the be the case.
This is pretty much my first Angular project, and I've just been going off of the docs, but there must be something I'm not seeing. Coming from other server side projects, the lack of stack trace is killing me haha.
Is there something I'm missing in the above code, that is preventing my template from being rendered in '/'?
Thanks!
This is my code and it is working fine, you cam take help from it.
var EventList = angular.module("EventList", ['ngRoute' ,'infinite-scroll']);
EventList.config(function($routeProvider) {
//$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl: 'views/business/business_home_events.html',
controller: 'EventListController'
});
});
EventList.controller('EventListController', ['$scope', '$http', '$route', function($scope, $http, $route){
// Do your work
}]);
the problem is with your when ('/'). Since your url has #/home - it looks in the .when to find that route.
change it to
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/home', { // <-
templateUrl: 'pages/home.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
}]);
This was an annoying one, but I think I figured it out.
I was encountering this issue while testing locally (no nodejs) on Chrome; however, sure enough when I popped it open in Safari it was working. It seems that ngRoute chokes on local files in Chrome.
I found a reference to the issue here, which is closed, so I'm guessing if I update to a newer version I shouldn't have this issue.
https://github.com/angular/angular.js/issues/4680
Setting up a web server should resolve this problem.
Why AngularJS routes are not working in local?
I have executed you code and is working fine on mozilla.
However, there is an issue in chrome of cross origin request if we run the file without putting in server.
But it is working fine on chrome also if you will put it on server (may be xampp/wampp) and run the file. The angular library you are using have http request to another server.
I have spent hours and hours searching and googling to find out why my ngRoute is not working but couldn't find the solution so i decided to come here. Here is my code::
"app.js"
angular.module("sandwichApp",["cart", "ngRoute"])
.config(['$routeProvider', function($routeProvider){
$routeProvider
.
when("/",{
templateUrl: "app/views/sandwichList.html",
controller: "SandwichListController"
}).
when("/sandwichList",{
templateUrl: "app/views/sandwichList.html"
}).
when("/checkout",{
templateUrl: "app/views/cart.html"
}).
otherwise({
redirectTo: "/app/views/sandwichList.html"
});
}]);
// for this particular code i have tried the version where the config() doesn't contain array "[]" but only the function and it also doesn't work
"sandwichListController.js"
var main = angular.module("sandwichApp", ["clientAppServiceModule"]);
main.controller("SandwichListController", function($scope, ClientAppService, cart){
$scope.original = {
sandwiches : []
}
//.... more code here. THERE IS NO PROBLEM WITH THIS CONTROLLER SO THE CODE IS NOT IMPORTANT.
);
"index.html"
<!DOCTYPE html>
<html ng-app="sandwichApp">
<head>
<meta charset="UTF-8">
<title>title</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-route.js"></script>
<!--script src="https://cdn.jsdelivr.net/angularjs/1.5.5/angular-route.min.js"></script-->
<script src="app.js"></script>
<script src="app/services/clientAppService.js"></script>
<script src="app/controllers/sandwichListController.js"></script>
<script src="app/model/cart.js"></script>
</head>
<body ng-controller="SandwichListController">
<div><strong>Heading & Cart</strong></div>
<div ng-view></div>
</body>
</html>
"sandwichList.html"
<div>
<b>Your Cart: </b>
{{totalItems}} items / {{totPrice | currency}}
<span>checkout</span>
</div>
<div>
<input type="text" ng-model="sandwichName" ng-change="filterSandwich()"/>
</div>
<div>
<h1>Sandwiches </h1>
</div>
<div ng-repeat="sandwich in workingCopy.sandwiches">
<h3 ng-click="addItemToCart(sandwich)">
<strong>{{sandwich.Name}}</strong>
<span>{{sandwich.Price | currency}}</span>
</h3>
</div>
When i load the "index.html" page, i expect the "otherwise" section of the routeer to display the "sandwichList.html" in the <div ng-view></div> section but it doesn't work. If it can't find the file, it will complain but it doesn't complain meaning that the file is at the right location. Yet it does not work.
In the sandwichList page at least if the controllers will not work, it must be able to display the <h1>Sandwiches </h1> .
My chrome console doesn't display any errors so i don't know what is causing the problem
I think it might be because you are accidentally declaring your app twice. When registering a new module in angular you provide it a second parameter which is an array of dependencies. You are doing that where you specify your routes. However, when you go to create your controller, you're code is this:
var main = angular.module("sandwichApp", ["clientAppServiceModule"]);
Angular sees the dependencies and assumes it is to create a new app. When it realizes there is already one with the same name, it overwrites it and you lose all the route stuff you setup. Try passing your "clientAppServiceModule" to the initial app definition, then just creating your controller by doing this:
angular.module("sandwichApp").controller("SandwichListController", function($scope, ClientAppService, cart){
$scope.original = {
sandwiches : []
}
//.... more code here. THERE IS NO PROBLEM WITH THIS CONTROLLER SO THE CODE IS NOT IMPORTANT.
);
Let me know if you have any questions, or if that doesn't solve it.
I tried some simple Angular Routing, but I cant specify what's the error. Chrome just tells me that Angular can't compile the Template.
In the following Link you can see my directory structure.
directory-structure
-- angular.js
var testApp = angular.module('testApp', ['ngRoute']);
testApp.config(function($routeProvider){
$routeProvider.when('/list', {
templateUrl: 'pages/list.html',
controller: 'mainController'
}).when('/insert', {
templateUrl: 'pages/new.html',
controller: 'newController'
});
});
testApp.controller('mainController', function($scope){
$scope.message = 'main';
});
testApp.controller('newController', function($scope){
$scope.message = 'new';
});
--index.html
<!DOCTYPE html>
<html lang="en" ng-app="testApp">
<head>
<meta charset="UTF-8">
<title>Barfly</title>
<script src="/angular/angular.min.js"></script>
<script src="/angular-route/angular-route.min.js"></script>
<script src="/js/angularApp.js"></script>
</head>
<body ng-controller="mainController">
list
new
<div id="main">
<div ng-view></div>
</div>
</body>
</html>
This is my error,
Browser Error
Thank you in advance!
EDIT. Sorry, I didn't see your directory structure. Are you sure pages directory is accessible to the public? Should the pages directory be moved into public directory?
Old answer:
The error is saying the templateUrl /pages/list.html does not exists. You should either save a template file into /pages/list.html file or add an inline template in the html body like this:
<script type="text/ng-template" id="/pages/list.html">
my template here
</script>
I encountered a sort of similar problem: templateUrl files could be not loaded (all resources didn't). In my case it happened when app was loaded on a browser on a mobile device. It was caused by Content Security Policy restrictions (How does Content Security Policy work?)
I got the CSP to permit all resources except for the templates referenced by templateUrl.
I also tried loading the templates through the script directive (https://docs.angularjs.org/api/ng/directive/script), but to no avail.
Eventually I decided to embed the templates in the route itself, like this:
testApp.config(function($routeProvider){
$routeProvider.when('/list', {
template: '<li ng-repeat="etcetera"></li>',
controller: 'mainController'
});
});
<a data-target="#list">list</a>
<a data-target="#insert">new</a>
Hello I have a weird problem with Angular UI-router. I was about to renew a webapp and want do this with Angular. I have heard a lot of good things about UI-router but I am not getting it to work. I am following the tutorial on how to set up views, but I get an error: Uncaught Error: [$injector:modulerr] Failed to instantiate module fqmApp due to:
TypeError: undefined is not a function
I am using cdn's to import angular and ui-router. This is my exact code:
<!doctype html>
<html ng-app="fqmApp">
<head>
<script src="https://code.angularjs.org/1.3.9/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.13/angular-ui-router.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ui-view>
</div>
<a ui-sref="state1">State 1</a>
<a ui-sref="state2">State 2</a>
</body>
</html>
JS
"use strict"
angular.module("fqmApp", ["ui.router"])
.config(function ($stateProvider, $urlRouterProvider) {
//For any unmatched url, redirect to /state1
$urlRouterProvider.otherwhise("/state1");
//Now set up the states
$stateProvider
.state('state1', {
url: "/state1",
templateUrl: "partials/state1.html"
})
.state('state2', {
url: "/state2",
templateUrl: "partials/state2.html"
});
})
.controller("ctrl", function ($scope) {
$scope.hello="hello";
})
Everything works fine if I don't include the config service code. I am not getting where I am going wrong here. The controller was just a test. It works fine. This is probably some silly mistake but I have been looking at it for an hour or more now.
Does somebody see the problem? Thanks in advance.
The problem with the code is that you have a typo, it should be otherwise instead of otherwhise Change this part:
$urlRouterProvider.otherwhise("/state1");
In this:
$urlRouterProvider.otherwise("/state1");