Why does my AngularJS app not work when I add routing? - javascript

I'm new to AngularJS, I actually started today and I wanted to create a sample site for a company using AngularJS. My plan was to create a view for the products and a view for the about page.
This is my index.html code:
<!doctype html>
<html ng-app="myApp" ng-controller="myCtrl">
<head>
<title>{{ title }}</title>
<script src="https://code.angularjs.org/1.5.0/angular.min.js"></script>
<script src="https://code.angularjs.org/1.5.0/angular-route.js"></script>
<script src="js/app.js"></script>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
</head>
<body>
<nav class="navbar navbar-default">
<div class="navbar-header">
<a class="navbar-brand"> {{ title }}</a>
</div> <!-- navbar-header -->
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li>Products</li>
<li>About</li>
</ul>
</div>
</nav>
<div ng-view></div>
</body>
</html>
And this is what I have in my app.js file:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope){
$scope.title = "My company site";
});
app.config(['$routeProvider', function($routeProvider){
$routeProvider.
when('/products', {
templateUrl: 'partials/home.html',
controller: 'productsController'
}).
when('/about', {
templateUrl: 'partials/about.html',
controller: 'myCtrl'
}).
otherwise({
redirectTo: '/products'
});
}]);
app.controller('productsController', function($scope){
$scope.message = 'This will show my products page';
});
app.controller('aboutController', function($scope){
$scope.message = 'This will show my about page';
});
Whenever I click on a link on my navbar the view for the clicked link doesn't get rendered. Also the title of the site is displayed like that {{ title }} on the browser. These problems started when I added the code for the routing. If I remove the code from the routing the title displays correctly. Also whenver I have the routing code on the site I get this error in my browser.
Uncaught Error: [$injector:modulerr] and it gives me a link to this page. I've visited the site and after checking everything the module seems to be loading fine only when I don't have the code for the routing in the app.js. So what am I doing wrong here? I'm looking at this for about an hour and I can't figure it out.

You're trying to use ngRoute, which is a separate module and needs to be installed and included separately. The error page links to another page, which specifically tells you that $routeProvider is unknown in your current project. See the ngRoute page for installation instructions: https://docs.angularjs.org/api/ngRoute.
Most specifically:
Then load the module in your application by adding it as a dependent module:
angular.module('app', ['ngRoute']);

var app = angular.module('myApp', ['ngRoute']);
Add the dependency. Worked for me.

You are not loading ngRoute in your app. To load it you should do something like this :
var app = angular.module('myApp', ['ngRoute']);

Change var app = angular.module('myApp', []); to var app = angular.module('myApp', ['ngRoute']); you're missing the module injection.

Related

ng-view doesn't show in index html page

My goal is doing routing page on web app.
I have writted 2 pages: index and home.
In index page, there is ng-view which is calling home page.
But browser doesn't show any home page.
Maybe I'm mistake to write script.js...
index.html:
<body ng-controller="productsCtrl">
<header ng-include="'header.html'"></header>
<div id="main">
<!-- angular templating -->
<!-- this is where content will be injected -->
<div ng-view>
</div>
</div>
</body>
scripts.js:
var app = angular.module('myApp', ['ngRoute']);
app.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/home', {
templateUrl: '../templates/home.html'
})
.otherwise({
redirectTo: '/home'
});
}]);
Someone can help men about this. Thanks
You have to use ng-app directive
<body ng-app="myApp">

AngularJS page not found. Home page injected into index template but not other pages

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

ngRoute not finding template

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.

How do you load partials from a non-standard directory in angular.js?

I have my angular app set up as a bundle within a Symfony app. Because of this restriction, the directory structure for the angular app is different. All public resources are symlinked to a static directory, including the partials. I got the app to load, the controllers fire, but none of the partials load for their specific controllers. I had this working as a standalone app (outside of Symfony), so I must be missing something with the new configuration.
index.html.twig:
note: the javascript files load just fine- that is the correct asset path
<body ng-controller="MainController">
<nav class="navbar navbar-default" role="navigation">
<div class="container">
<ul class="nav navbar-nav navbar-right">
<li class="active">Home</li>
<li>Groups</li>
</ul>
</div>
</nav>
<div ng-view=""></div>
<div ng-view></div> <!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please upgrade your browser to improve your experience.</p>
<![endif]-->
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
<script src="bundles/translations/webadmin/app/js/ngroute.js"></script>
<script src="bundles/translations/webadmin/app/js/app.js"></script>
<script src="bundles/translations/webadmin/app/js/services.js"></script>
<script src="bundles/translations/webadmin/app/js/controllers.js"></script>
<script src="bundles/translations/webadmin/app/js/filters.js"></script>
<script src="bundles/translations/webadmin/app/js/directives.js"></script>
</body>
app.js:
note: I tried making templateUrl just partials/ as well
angular.module('myApp', [
'ngRoute',
'myApp.filters',
'myApp.services',
'myApp.directives',
'myApp.controllers'
]).config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/groups', {templateUrl: 'bundles/translations/webadmin/app/partials/groups.html', controller: 'GroupsController'});
$routeProvider.when('/', {templateUrl: 'bundles/translations/webadmin/app/partials/home.html', controller: 'HomeController'});
$routeProvider.otherwise({redirectTo: '/'});
}]);
controllers.js
note: the alerts fire just fine, but the partials don't load...
angular.module('myApp.controllers', [])
.controller('MainController', ['$scope', function($scope) {
alert('here?');
}])
.controller('HomeController', ['$scope', function($scope) {
alert('here2');
}])
.controller('GroupsController', ['$scope', function($scope) {
// TODO see below
}]);
console output:
Consider using 'dppx' units, as in CSS 'dpi' means dots-per-CSS-inch, not dots-per-physical-inch, so does not correspond to the actual 'dpi' of a screen. In media query expression: (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) translations:1
Blink is considering rejecting non spec-compliant cross-origin web font requests: https://d3nkxvtkt5c8vi.cloudfront.net/0.4.2/fonts/proxima_nova_light_0.woff. Please use Access-Control-Allow-Origin to make these requests spec-compliant.
Any idea what I am missing here? Any help would be greatly appreciated.
It looks like the problem you have is that ng-view is missing from your index markup.
<div ng-view=""></div>
Without this element, your controllers will load, but have no place to insert your view templates.
You can read more about it here

Angular.js : How to use ng-href in template?

I try to create a simple SPA with 1 index.html which include templates.
I got a problem with ng-href directive:
<a ng-href="#/myPage">myPage</a>
work in index.html but not in my templates, the link is unclickable. but href still works.
myPage
My app :
index.html:
...
<body ng-app="myApp">
<a ng-href="#/myPage" target="_self">link</a> <!-- work ! -->
<div class="container" ng-view=""></div>
</body>
...
app.js:
'use strict';
angular.module('myApp',
[ 'ngCookies', 'ngResource', 'ngSanitize', 'ngRoute' ]).config(
function($routeProvider) {
$routeProvider.when('/', {
templateUrl : 'views/main.tpl.html',
controller : 'MainCtrl'
})
.when('/myPage', {
templateUrl : 'views/page.tpl.html',
controller : 'MainCtrl'
})
.otherwise({
redirectTo : '/'
});
});
controller.js
'use strict';
myApp.controller('MainCtrl', function() {
this.myColor = 'blue';
});
page.tpl.html
<div>
<a ng-href="#/myPage" target="_self">link</a> <!-- Dont work -->
<a ng-href="#/myPage" target="_self">link</a> <!-- Dont work -->
<a ng-href="#/myPage{{}}">link</a> <!-- Dont work -->
<a ng-href="#/{{ 'myPage' }}">link</a> <!-- Dont work -->
link <!-- Work ! -->
</div>
I don't understand the problem with ng-href and why the result is different than href.
I use angular 1.2
ngHref is used to dynamically bind angular variables to the href attribute like so:
<a ng-href="#/{{myPathVariable}}"/>Take Me Somewhere</a>
Where in your scope:
$scope.myPathVariable = 'path/to/somewhere';
Then after angular compiles it, it looks like this:
<a ng-href="#/path/to/somewhere" href="#/path/to/somewhere" ... other angular attributes>Take Me Somewhere</a>
If your path is hardcoded into the page (you know where the link should take you on page load), you can just specify it in an href, which is why your third example works. Only use ngHref when you need angular to decide the route dynamically after the JS loads. This prevents your user from clicking links and going to an invalid route before angular has deciphered where the link should point. Documentation here

Categories

Resources