I have html file which implements AngularJS routes as follows,
index.html:
<!DOCTYPE html>
<html ng-app="demo">
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div ng-view>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.1/angular-route.min.js"></script>
<script>
// Code goes here
var demo = angular.module('demo', ['ngRoute']);
demo.config(function($routeProvider){
$routeProvider.when('/', {
controller: 'testController',
templateUrl: 'test.html'
})
})
var controllers = {};
controllers.testController = function($scope){
$scope.first = "Info";
$scope.customers=[
{name:'jerry',city:'chicago'},
{name:'tom',city:'houston'},
{name:'enslo',city:'taipei'}
];
}
demo.controller(controllers)
</script>
</body>
</html>
test.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>
You can find the working version here
But why is it not working when I run the same in my local browser :(
Here is the chrome console error:
Any help appreciated! :)
It is important to make it clear. For security reasons, Chrome (for example) won't allow you to load local files (ie: the templates for your views). My suggestion is to set up a web server to test your applications:
Use the free edition of the Visual Studio Express for web development.
Use gruntjs to quickly set up your project.
Alternatively you can use inline templates in place of loading it externally, but it does not seems to be a good practice.
Edit:
Using the console error print that you posted, Chrome is blocking your ajax request. You can bypass this restriction using a command line argument:
chrome.exe --allow-file-access-from-files
However I would encourage you to set up a simple local web server, It will prevent you for some headaches while your are learning...
You can use Firefox for test. Route and ajax will work.
But it is better to set up a web server like #gustavodidomenico said
the work around to make ng-view work in local is to put the content of other htmls in the script tag as
<script type="text/ng-template" id="index22.html">
This is index 2 template.
</script>
<script type="text/ng-template" id="index33.html">
This is index 3 template.
</script>
in the same HTML from where the call is being made.
ngview makes an AJAX call to load the content of external HTMLs or seperate HTMLs , chrome does not allow AJAX call for local resources , IE 11 also shows 'Access is denied' error message.
when including in script tags , this AJAX call is not made.
There is a Chrome Extension called Web Server for Chrome. you can add it and then lunch it, in browse dialog choose your working folder, then it gives you a Local URL, you can test your app there.
Related
A very basic question
Cannot load external javascript resource on server
I am working on a Play framework project. I've made some basic html view with some Javascript. It works correctlly when I have my js code in the actual view.
However, when I tried moving js code to a separate file and load it using
<script> src="main.js" </script>
It works correctly when opened using plain chrome browser. However when I run it on server and it fails and chrome dev console prints the following message
GET http://localhost:9000/main.js 404 (Not Found)
I've tried setting up a GET request on targer URL but cannot pass main.js as an arguement to Ok method
def getmainJs()= Action {
Ok()
}
Is there a painless way to access the js code or do I have to go through the process of setting up the JavacriptRouter menntioned here. The app is only going to be 2 views to I kind of don't care about scalability
I created an example on how to serve a Javascript file:
Routes:
GET /foo sk.ygor.stackoverflow.q53319493.controller.ApplicationController.foo
GET /assets/*file controllers.Assets.versioned(file)
View:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="#routes.Assets.versioned("main.js")"></script>
</body>
</html>
I am decomposing the Angularjs branch of the Spring petclinic sample app to figure out how it works. Towards that end, I deleted the entire contents of src/main/webapp/ and replaced it with:
src/main/webapp/resources/css/bootstrap.cs
src/main/webapp/resources/css/my.css
src/main/webapp/js/lib/angular.js
src/main/webapp/includes/index_testincl.html
src/main/webapp/testController.js
src/main/webapp/index.html
There is nothing else in src/main/webapp/ besides the 6 files listed above.
The Spring config files remain the same and are at this link.
The stripped and minimally-replaced version works perfectly in Eclipse on a local devbox when called from localhost:8080/appname, but when I bundle it into a war file and upload it to a remote server, it is not able to serve the JavaScript, CSS, or HTML include files that are a critical part of its functioning. What do I need to change in the setup in order to get the Angularjs functionality to work properly in the remote web server when someone types mydomain.com into their browser?
There is no CSS or JavaScript in the content served by the remote web server, so there are no links. There is only plain text. When I have the network tab of the developer tools open in Firefox, the following output is displayed:
There is no console tab output for any of the above requests.
The goal is to better understand how the connection between AngularJS and Spring MVC needs to be set up. The more sophisticated versions built up from these simple files need to do database transactions using Java and Spring MVC. Thus, any answer needs to be compatible with Java and Spring MVC.
The Tomcat server that serves up mydomain.com at the remote web server also successfully serves up other war files that are spring-only using jsp, so the problem is related to adding AngularJS and HTML.
Note: The exact clone of the AngularJS Spring petclinic app also does not run when bundled into a war and deployed at mydomain.com, but this OP uses a greatly simplified AngularJS app in order to more effectively isolate the specific mechanism required to get Tomcat, spring-mvc, and AngularJS to work together on a web server.
Steps to recreate this problem
The problem can be recreated with the following steps:
1.) Navigate to /home/username/git
2.) git clone https://github.com/singularity-sg/spring-petclinic.git
3.) Eclipse -> File -> Import -> Maven -> Existing Maven project
4.) Eclipse -> Project Explorer -> Rt-Click-Project -> Maven -> Download Sources
5.) Eclipse -> Project Explorer -> Rt-Click-Project -> Maven -> Update Project
6.) Delete everything in src/main/webapp except keep: src/main/webapp/js/lib/angular.js
7.) Download bootstrap.css version 3.3.5 from this url: http://getbootstrap.com/getting-started/ (It is in a zip file.) Once it is downloaded, copy it to the following location in the project: src/main/webapp/resources/css/bootstrap.cs (You will need to create the src/main/webapp/resources/ and src/main/webapp/resources/css directories.)
8.) Create src/main/webapp/resources/css/my.css to include whatever minimal styles you want.
9.) Create src/main/webapp/index.html and add the following:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title of page</title>
<link rel="stylesheet" type="text/css" href="resources/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="resources/css/my.css">
</head>
<body ng-app="testApp">
<script src="js/lib/angular.js"></script>
<script type="text/javascript" src="testController.js"></script>
<div ng-controller="testController">
<table width=100%>
<tr>
<td align=center>
<table>
<tr>
<th class="toc">
<a class="btn btn-success" role="button" ng-click="homeFunc()">Home</a>
</th>
<th class="toc">
<a class="btn btn-success" role="button" ng-click="testFunc()">Include file</a>
</th>
</tr>
</table>
</td>
</tr>
<tr>
<td align="center">
<div ng-if="functype == 'home'">
Home page.
</div>
<div ng-if="functype == 'test'">
<div ng-include="'includes/index_testincl.html'"></div>
</div>
</td>
</tr>
</table>
</div>
</body>
</html>
10.) Create src/main/webapp/includes/index_testincl.html and include the following code:
<table>
<tr>
<td>
<p class="body">If the link shows this, then JavaScript works!</p>
</td>
</tr>
</table>
11.) Create src/main/webapp/testController.js and include the following:
// create Angular app
var testApp = angular.module('testApp', []);
// create Angular controller
testApp.controller('testController', ['$scope', '$http', function($scope, $http) {
$scope.functype = 'home';
//below functions handle navigation links
$scope.homeFunc = function() {
$scope.functype = 'home';
}
$scope.testFunc = function() {
$scope.functype = 'test';
}
}]);
12.) Eclipse -> Project Explorer -> Rt-Click-Project -> Run As..Maven Build
13.) Eclipse -> Project Explorer -> Rt-Click-Project -> Refresh
14.) Copy the way to some remote Tomcat server and try to load it from a web browser by typing anydomain.com.
That is it. The problem should be recreated.
What needs to be changed in order for the above minimal AngularJS app to run properly on the remote Tomcat web server when requests are made to anydomain.com?
I am new to AngularJS.
I want to include reusable html in the main html. When I try to redo this example, it fails. Currently I have myUsers_List.htm, myUsers_Form.htm, myUsers.js, and main.html all in one folder.
The code in main.html is as follow:
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body ng-app="myApp" ng-controller="userCtrl">
<div class="container">
<div ng-include="'myUsers_List.htm'"></div>
<div ng-include="'myUsers_Form.htm'"></div>
</div>
<script src= "myUsers.js"></script>
</body>
</html>
I can see the content in myUsers_List.htm and myUsers_Form.htm when I open main.html in Dreamweaver, but when I open it in browser, it's blank.
Could someone help me out the problem about that? Is is about the path of files or some other issue? Thanks.
When I try to check it out in the Chrome JavaScript debugger to see whether there is any error.
Since your error is
XMLHttpRequest cannot load file:///C:/Users/Desktop/New%20folder/myUsers_List.htm. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
It seems that you need to run your angular app from a web server instead of trying it locally.
You need to either run your project under a webserver, xampp is simple to setup.
You could perhaps download angularjs and bootstrap and serve them locally from the file system, at the minute you're using a cdn.
Also, just an observation, you're missing your tag, on mobile so can't test if that'd cause any issues.
I have been working a bit with Angular and I tried to implement simple routing.
I have a basic HTML which contains reference to all the required scripts and a ng-view tag.
For some reason, when the page is loaded, the template isn't shown in the ng-view location. Why isn't it shown, and how to fix it?
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-route.js"></script>
<script src="routCtrl.js"></script>
</head>
<body ng-app='ngRouteTest'>
<div ng-view></div>
</body>
and the the script file:
var ngRouteTest = angular.module('ngRouteTest',['ngRoute']);
ngRouteTest.config(function($routeProvider){
$routeProvider
.when('/',
{templateUrl : '/routView1.html'})
});
You need to redirect to that page so that routing will come to know which page to render inside ng-view directive.
There are multiple ways to do it.
Define one more otherwise to redirect to /.
$routeProvider.otherwise({redirectTo: '/'})
Add anchor to page that will redirect to /.
<body ng-app='ngRouteTest'>
Home Page
<div ng-view></div>
</body>
Having default url on page in <head> tag.
<base href="/"/>
Okay first you need to run your code from a server, so to test it locally use http-server which is really easy to prepare.
Then you will need to change your templateUrl path from:
{templateUrl : '/routView1.html'}
to:
{templateUrl : './routView1.html'}
After starting a local host and ruining the code from there it worked perfectly fine.
The issue was with the chrome related security when you make local ajax calls.
So one has this problem should do one of the following things:
1.Disable web-security in chrome.
2.Start a local host to test.
I'm developing an application in .net mvc with angularjs. When I don't use html5 mode it works fine, but when I set html5 mode to true the server calls that address giving me an he resource cannot be found.
This is my app.js
var app = angular.module("myApp", ['ngRoute'])
.config(function ($routeProvider, $locationProvider) {
$routeProvider.when('/test',
{
templateUrl: 'templates/TestPage.html',
controller: 'ProfesionalController'
});
$routeProvider.otherwise({ redirectTo: '/' });
$locationProvider.html5Mode(true);
});
And this is my view (layout):
<!DOCTYPE html>
#Scripts.Render("~/bundles/modernizr")
<script src="~/Scripts/angular/angular.js"></script>
<script src="~/Scripts/angular/angular-route.js"></script>
<script src="~/app/app.js"></script>
<script src="~/app/home/home.js"></script>
<script src="~/app/profesional/profesional.js"></script>
<base href="/">
Test
#*this is the link*#
</div>
</div>
</div>
<div ng-app="myApp" class="container body-content">
<div ng-view></div>
#RenderBody()
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
When I click to test link the server try to locate:
http://localhost:39881/test" giving me an 404 Not Found - http://localhost:39881/test"
What I'm missing. It works well with no html5 mode.
Even I was facing the same issue when I was trying to enable html5 mode in my application. Later when I saw the entire code carefully, I came to know the name of my API call and my route call were same. The browser was getting confused and instead of calling route call it was calling the api call.
Try changing either of the name. It should work fine.
You need to configure your server side rewrites so it doesn't try to load up pages at that path. See details for your server type here: https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode
Something that cost me a lot of time that hopefully will help others if you are using Azure and a pure ng app:
I am using Azure and Angular and hit the same problem. I had the IIS Rewrite rules to redirect all requests to the index.html file as per the documentation in ng.
However, it still was not working on production, only on local. It turned out to be a stupid user error - my Angular webapp is a pure HTML/JS app (ie. no ASP.NET MVC) and the Azure Publishing Profile had not marked the web.config for dpeloyment to the cloud. I used Kudu on Azure to check the webapp and there was no web.config on live, hence the rewrite rules were not being considered... changing it to FileType Content solved the issue so the web.config was deployed correctly and the routing now works..