Angular.js templates not loading - angularjs

I am new to angular.js and just trying to get my head around the basics and hopefully this is something simple, but I am having trouble loading in a templateUrl.
My index.html is as follows:
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>AngularJS Tutorials</title>
</head>
<body>
<div ng-app="app">
<h1>Introduction to Angular.JS</h1>
<div ui-view></div>
</div>
<!-- Scripts -->
<script type="text/javascript" src="js/angular.min.js"></script>
<script src="js/angular-ui-router.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
My app.js is:
angular
.module('app', [
'ui.router'
])
.config(['$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'templates/home.html'
})
}])
My home.html is: <h1>home template</h1>
So I dont know why this isn't working, but the error is:
XMLHttpRequest cannot load file:///Users/code/Desktop/angular/templates/home.html. Cross origin requests are only supported for HTTP.
Thanks in advance, Gab

This error comes due to a security restriction put by the browser. You can try below steps:
Try to run your code in some other browsers
Add the templates inside index.html itself by placing the content inside script tag. These script elememts should appear after ng-app. (ref link)
<script type="text/ng-template" id="home.html">
Content of the template goes here
</script>

First thing you use <ng-view> </ng-view> for loading your templates. and second is use <script type="text/ng-template" id="home.html"> for you each partial view. third thing is not mandatory but use otherwise at last that makes sense. Here is fiddle for you check it out
fiddle

If you want to run your page locally, I suggest you install a http-server and run it in there ...
Then you avoid CORS issues like that
Example:
with node.js installed
cd ~/myProjectFolder
npm i http-server
http-server ./
Then you could also just enter localhost:8080 in your browser and wouldn't have to point it to some URI/folder

Related

AngularJS NgRoute - Url Changes But view doesnt render,No errors

appscript.js
var myApp=angular.module('myApp',['ngRoute']);
myApp.config([$routeProvider,function($routeProvider) {
$routeProvider
// route for the home page
.when('/home', {
templateUrl: 'home.html',
controller: 'homeController'
})
// route for the about page
.when('/services', {
templateUrl: 'services.html',
controller: 'servicesController'
})
// route for the contact page
.when('/contacts', {
templateUrl: 'contacts.html',
controller: 'contactsController'
})
.otherwise({ redirectTo: '/services' });
}
]);
index.html
<!doctype html>
<html ng-app="myApp">
<head >
<script src="appscript.js"></script>
<link href="Styles/Styles.css" rel="stylesheet">
<script src="homeController.js"></script>
<script src="servicesController.js"></script>
<script src="contactsController.js"></script>
<script src="aboutController.js"></script>
<script src="clientsController.js"></script>
<script src="angular-route.min.js"></script>
<script src="angular.min.js"></script>
</head>
<body >
<div class="header" > <h2 style="color:blue;">Training Institute</h2>
</div>
<div class="nav">
Home
About
Services
Clients
Contact
</div>
<div class="content" >
<ng-view> </ng-view>
</div>
<div class="footer">footer</div>
</body>
</html>
homeController.js
angular.module('myApp').controller('homeController',function($scope)
{
$scope.message="i am in home controller";
}
);
home.html
<div>i am in home partial template</div>
I have searched related questions and did many changes but still not able to load partial templates in the view.The url is changed but the veiw doesnt update.
I put all my code files in the same location where index.html is there,to make sure the issue is not because of incorrect paths.
I've created a plunkr to reproduce and fix your problem which you can find here: https://plnkr.co/edit/oTB6OMNNe8kF5Drl75Wn?p=preview (note: only home, services and contacts work, as those are the only routes configures in ur code so the rest falls back to the route specified in otherwise)
There are two issues with your code:
You're order of files is incorrect, it needs to be:
<script src="angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="appscript.js"></script>
<script src="homeController.js"></script>
<script src="servicesController.js"></script>
<script src="contactsController.js"></script>
<script src="aboutController.js"></script>
<script src="clientsController.js"></script>
You're using AngularJS 1.6, in order to use routing ensure to read my answer here: Angular routing with ng-view is not working
Long story short: As of AngularJS 1.6, the default value for hashPrefix is !. As you're not making use of it, you either have to use it or reset it to '' using $locationProvider.hashPrefix(''). This change was introduced as of AngularJS 1.6 due this commit: https://github.com/angular/angular.js/commit/aa077e81129c740041438688dff2e8d20c3d7b52
Note: If this still doesn't help you, we might need more information as we have no idea what the content of all those js files are. Feel free to update my plunkr to reproduce your problem in that case.

How can I use angularjs ui-router without a server i.e. running it from a folder on my computer?

I want to be able to quickly build an AngularJS application using ui-router without having to set up a server. So that I can send this folder to anyone and the application will still work.
I have tried putting a # infront of the route as adviced here. I have also tried to follow other advice related to the ngroute, but nothing seems to work and since I want to use ui-router rather than ng-route I'm not sure whether the advice is even applicable to my situation.
I have also tried to create a manifest file to store the files offline according to this page.
In firefox it kind of works but for some reason it double up what is on the index.html page. But in chrome which is my preferred browser it doesn't work at all. I get an error about a failed ajax call; why don't the manifest file download all pages straight away?
How should I accomplish building an AngularJS app with ui-router without needing a server?
Here is simple snippet of my code:
index.html
<!DOCTYPE html>
<html lang="en" ng-app="app" manifest="mycache.manifest">
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<a ui-sref="home.messages">Messages</a>
<div ui-view></div>
<script type="text/javascript" src="bower_components/angular/angular.js"></script>
<script type="text/javascript" src="bower_components/angular-ui-router/release/angular-ui-router.js"></script>
<script src="js/routes.js"></script>
<script src="js/main.js"></script>
</body>
</html>
messages.html
<button ng-click="contextCtrl.getAllMessages()">Get Messages</button>
<div ng-repeat="message in contextCtrl.messages">
{{message}}
</div>
routes.js
'use strict';
angular.module('app', ['ui.router']);
//Setting up route
angular.module('app').config(['$stateProvider',
function($stateProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'index.html',
controller: 'ContextCtrl',
controllerAs:'contextCtrl'
})
.state('home.messages', {
url: '/messages',
templateUrl: 'messages.html',
controller: 'ContextCtrl',
controllerAs:'contextCtrl'
});
}
]);
main.js
'use strict';
/*jslint latedef:false*/
//Controller declaration
angular.module('app').controller('ContextCtrl', ContextCtrl);
function ContextCtrl() {
var vm = this;
vm.messages = [];
vm.getAllMessages = getAllMessages;
function getAllMessages(){
vm.messages = ['m1', 'm2', 'm3', 'm4'];
};
}
mycache.manifest
CACHE MANIFEST
js/main.js
js/routes.js
messages.html
bower_components/angular-ui-router/release/angular-ui-router.js
bower_components/angular/angular.js

AngularJS Partial Not Loading

Writing a very simple angular js app to learn routes and partials. The problem is that my would just not load the partial template at all.
index.html
<!DOCTYPE html>
<html ng-app="website">
<head>
<title>Hello World, AngularJS</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.js"></script>
<script type="text/javascript" src="../js/website.js"></script>
</head>
<body>
<ul>
<li><a href='/'>Home</a></li>
<li><a href='/login'>Login</a></li>
<li><a href='/about'>About</a></li>
</ul>
<ng-view></ng-view>
</body>
</html>
website.js
angular.module('website', ['ngRoute']).
config(function ($routeProvider, $locationProvider) {
$routeProvider.
when('/about', {templateUrl: 'partials/about.html'}).
when('/login', {templateUrl: 'partials/login.html'}).
otherwise({redirectTo:'/'});
$locationProvider.html5Mode(true)
});
When I load index.html, it shows the links. When I click on one of the them, or go manually to #/about, it should load the contents of the template inside ng-view, but it doesn't.
The about.html and login.html are just two files with a single tag in them with Hello World text. What am I missing? I was earlier not including angular-route.js, but fixing that didn't work.
My directory structure goes like this:
views
--js
--website.js
--views
--index.html
--partials
--about.html
--login.html
The network says that it did GET about, but brings me back to index.html without anything in ng-view

Routing Function in AngularJS Does Not Get Executed

Newbie with AngularJS here.
I have an index.html file below, which references an Javascript file named app.js. The index.html file is as below:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script data-require="angular.js#*" data-semver="1.2.22" src="https://code.angularjs.org/1.2.22/angular.js"></script>
<script data-require="angular-route#*" data-semver="1.2.20" src="https://code.angularjs.org/1.2.20/angular-route.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="app.js"></script>
<script src="controller1.js"></script>
</head>
<body>
<h1>Github Viewers</h1>
<div ng-view></div>
</body>
</html>
In my app.js file, I have the following codes:
(function(){
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider){
$routeProvider
.when("/main", {
templateUrl: "main.html",
controller: "controller1"
})
.otherwise({redirectTo: "/main"});
});
}());
I've set breakpoints (in Chrome Dev Tools) on the line:
templateUrl: "main.html",
But I am unable to get into this line.
Console Window shows no errors, so I am a little stumped.
Appreciate any insight on where to look further on this.
You are using the wrong app name.
Change <html ng-app="myApp"> to <html ng-app="githubViewer">
Edit
You cannot put a breakpoint in that line (templateUrl: "main.html"). Note that's an Object definition and not a function:
{
templateUrl: "main.html",
controller: "controller1"
}
And like all Objects, they are defined in an atomic operation. It's like if all its properties were created at once, meaning that you cannot "break" the execution for a specific property.
I've tested with Chrome dev tools and it doesn't even allow me to set a breakpoint in that line. Not sure how you did it...
If you want to check if the "main.html" template is being loaded, watch the network tab of the Chrome dev tools.
I think your dependency injection is missing controller1 module..
if you managing controllers in different module you have to inject it in your app.js
//controller1.js
angular.module('controllers',[])
.controller('controller1',function(....)
//app.js
var app = angular.module("myApp", ["controllers","ngRoute"]);
...
//index.html
...
<script src="controller1.js"></script>
<script src="app.js"></script>
...

AngularJS writing an app with no server

I'm trying to write an AngularJS client side only app.
I thought I might be able to load it from chrome by typing in the address bar:
file:///C:/path/to/project//index.html
I also tried to invoke chrome with the flag --allow-file-access-from-files
Unfortunatly nothing happened - just the busy sign on the tab name is working.
Why does is not loading my app?
I'm using the following code:
index.html:
<!doctype html>
<html ng-app="app">
<head>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular-route.js"></script>
<script src="app.js"></script>
<title></title>
</head>
<body style="background-color: white;">
<h1>Index</h1>
<a id="link" href="/login">Go to login</a>
<ng-view></ng-view>
</body>
</html>
app.js:
angular.module('app', ['ngRoute']).
config(function($routeProvider) {
$routeProvider.
when('/', {controller: HomeCtrl, templateUrl: 'app.html'}).
when('/login', {controller: LoginCtrl, templateUrl: 'login.html', resolve: function() {}}).
otherwise({redirectTo:'/'});
});
function HomeCtrl($scope) {
$scope.numbers = [1,2,3,4,5];
}
function LoginCtrl($scope) {
}
app.html:
<div ng-controller="HomeCtrl">
<ul ng-repeat="number in numbers" >
<li>{{number}}</li>
</ul>
</div>
Edit:
2 possible solutions:
Close all chrome instances and run from command line: "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files --allow-file-access
Run Firefox which does not have this restriction (Like #GeekBoy mentioned)
As far as I know google chrome does not allow javascripts to be run from file system. But I did a quick google search and found this. Might be useful
Link
On the flipside you can use firefox. Firefox doesn't have such restrictions as far as I know
Try changing the following lines:
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular-route.js"></script>
to
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular-route.js"></script>
I think since you're using a file-based way to get at index.html, it's assuming the // also points to a local system resource. By specifically indicating http://, it will look at the actual locations.
I know that this is an old question but for anyone that might still be interested, here is a small project that demonstrates how to write an angularjs client-side app. It is a complete AngularJS 1.63 single page application with routing that does not need a web server: https://github.com/jlinoff/aspa-nows.
There were two key challenges to getting it working: getting the the page href references right because of the newly introduced default hash prefix: ! (see aa077e8 for details), and embedding the template HTML code into index.html as ng-template scripts to avoid CORS errors. Once those fixes were made, it worked as expected.
The project README.md explains what needed to be done in detail and the full source code is available.

Resources