New to angular and I've been having trouble with what should be a simple directive for the past hour or so. Would really appreciate some help!
I believe hello should appear, can't seem to get it to work?
test.html
<html>
<head lang="en">
<title>Test</title>
</head>
<body>
<div ng-app="myApp">
<hello></hello>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.14/angular.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
main.js
var myApp = angular.module('myApp', []);
myApp.directive("hello", function() {
return {
restrict: 'E'
templateUrl:"hello.html"
};
})`
hello.html
<p>Hello</p>
If you are testing locally and using Google Chrome then this will not work because AngularJS is making an Ajax call to these html files, but Chrome blocks this with the error:
XMLHttpRequest cannot load file:///[filepath...] Cross origin
requests are only supported for protocol schemes: http, data, chrome,
chrome-extension, https, chrome-extension-resource.
You can verify this by opening up your developer console and viewing the errors.
To get around this a couple ways:
You can create a simple web server to run your code. If you have python you can just run the command (EDIT: from your folder containing index.html):
python -m SimpleHTTPServer
You can disable same origin policy in Chrome:
https://stackoverflow.com/a/6083677/1100379
Use an Chrome extension which may do this for you. I looked one up and this was the first result:
Allow-Control-Allow-Origin
Everything works fine, just make sure your syntax is correct.
Do not miss comma's in JSON
myApp.directive("hello", function() {
return {
restrict: 'E',
^
templateUrl:"hello.html"
};
})
Demo: http://plnkr.co/edit/Z6rjbsuqzmcD4gBem36c
Actually we need to give the relative path for the templateUrl directive. Relative path which totally depends on component file in which you are giving path.
lets assume your file path may be like - app/hello.html
then your templateUrl path should be like - templateUrl:"./hello.html"
open dev tools in chrome go to network tab find reqest for hello.html compare reqested path with your path to hello.html on server. Move hello.html in proper place or update templeteUrl
Open your NodeJS command propmpt and install http-server using npm install http-server
http-server is a simple zero configuration command-line http server.
Once installed, just use http-server -o in your NodeJS command prompt.
Download Python and add it to you path environment variable
Create a cmd file to start python server in the directory where your index.html stays.
2 a) Create a new text document in the same root as your index.html
2 b) write - python -m SimpleHTTPServer 8080
2 c) Save as type 'All Files' and with some name like startServer .cmd
Now the workaround for failing AJAX call has been done. Oen in browser 127.0.0.1:8080/index.html
You can import template in the script and use it as a "template", not "templateUrl":
import hello from 'hello.html';
var myApp = angular.module('myApp', []);
myApp.directive("hello", function() {
return {
restrict: 'E'
template: hello
};
})
You can use:
userManagementApp.directive("ngCreateUserForm", function () {
return {
templateUrl : '/template/create.html'
};
});
and in Server side, you must serve youre template like static file
in Go: e.Static("/template", "/path/to/static/folder")
or
in httpd config:
Alias /template/ "/path/to/template/folder"
Related
How to remove #! getting added to url in my AngularJS application?
I have tried:- $locationProvider.html5Mode(true).hashPrefix('!'); and adding <base href="/"> but to no avail. When I navigate to a particular url, #! disappears but when I tried to reload, it gives the error:- Cannot GET.
So I looked online, and found out that doing above is only half of the solution. We also need to rewrite the logic on server side as well. So I am using NodeJS and browserSync package to fire up localhost. So what is the solutioin to this?
Note:- My backend and frontend code are separate and both handle routing.
There is a option in Browsersync called single which serves the index.html as a fallback if the url does not exist.
Serve an index.html file for all non-asset routes. Useful when using client-routers
See documentation:
https://www.browsersync.io/docs/options#option-single
browserSync.init({
server: {
baseDir: 'dist',
},
single: true
});
I am trying to run the google-cdn plugin via Gulp (gulp-google-cdn) to covert bower references in my HTML file into the CDN equivalent. Gulp-google-cdn does not do anything, and enabling the DEBUG, shows: google-cdn Could not find satisfying version for angular-material ^1.0.5
My task (I use a subdirectory with tasks per file):
gulp.task('HTML:Release', function() {
return gulp.src('../src/*.html')
.pipe(googleCdn(require('../bower.json')))
.pipe(gulp.dest('../dist/') )
;
});
HTML:
<!DOCTYPE html>
<html ng-app="OntarioDarts" ng-cloak lang="en">
<head>
</head>
<body layout="row" ng-cloak>
<div layout="column" class="relative" layout-fill role="main">
<md-content flex md-scroll-y>
<ng-view></ng-view>
</md-content>
</div>
</body>
<!-- Load JavaScript Last for Speed. Load from CDN for cache speed -->
<!-- Angular JS -->
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-material/angular-material.min.js"></script>
<script src="bower_components/angular-material-icons/angular-material-icons.min.js"></script>
The distribution file does not point Angular to the CDN, but still tries to use the bower_components, even though it did not complain that the files were not found.
One problem I found is that I have Angular set at ^1.5.0 in my bower.json. However, I was only using the default Google CDN, which does not currently have the 1.5.0 available. I changed the version in the bower.json file to be ^1.4.0, and then the file was changed to use the CDN with version 1.4.7.
The problem though is that the reference did not get changed to HTTPS://, but was left simply as src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"
Gulp-google-cdn does not do anything, and enabling the DEBUG, shows: google-cdn Could not find satisfying version for angular-material ^1.0.5
That's because the newest version available from the Google CDN is 1.0.4.
The problem though is that the reference did not get changed to HTTPS://, but was left simply as src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"
That's not necessarily a problem. That's a protocol-relative URL. If your page is served over HTTP, angular.min.js is fetched over HTTP. If your page is served over HTTPS, angular.min.js is fetched over HTTPS.
Unless you absolutely need angular.min.js to always be fetched over HTTPS you can just leave it like that.
EDIT: ... except for when you're trying to open a local HTML file in a browser. Then your protocol is file:// and the protocol relative URL will refer to your local file system. Which of course leads nowhere.
One way of fixing this would be to serve your html files through a locally running webserver (e.g. with gulp-webserver). When your HTML pages come from e.g. http://localhost:8000/ all the protocol relative URLs will be served over http:// as well.
If you just want all the CDN URLs to be prefixed with https:// instead, here's a way to wrap the google-cdn-data object to achieve this:
var gulp = require('gulp');
var googleCdn = require('gulp-google-cdn');
var jp = require('jsonpath');
function protocol(proto, cdn) {
jp.apply(cdn, '$.*.url', function(url) {
return function(version) {
return proto + url(version);
};
});
return cdn;
}
gulp.task('HTML:Release', function() {
return gulp.src('../src/*.html')
.pipe(googleCdn(require('./bower.json'), {
cdn: protocol('https:', require('google-cdn-data'))
}))
.pipe(gulp.dest('../dist/') );
});
You'll need to run npm install --save-dev google-cdn-data jsonpath for this to work.
I have created a drop down list where it's values are stored in a JSON file.
I am capable of fetching the data from the file in Firefox, but am not able to do the same in Chrome, or other browsers.
Here is my HTML page:
<!doctype html>
<html>
<head>
<title>angularjs phone number validation</title>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<script src="http://code.angularjs.org/1.2.9/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="myApp" ng-controller="ProductCntrl">
Type of Employeement:<select ng-model="initialProduct" ng-options="p.name for p in Products"></select>
</body>
</html>
Here is my JavaScript:
var app = angular.module('myApp', []);
app.controller('ProductCntrl', function ($scope,$http) {
$http.get('json1/student.json') //reading the studentRecord.json file
.success (function(json1){
$scope.Products = json1; // binding the json1 to the $scope variable
console.log($scope.Products[0].id);
$scope.initialProduct = $scope.Products[0];
});
});
json1 is the folder name and student.json is the file where I have stored the json data.
This my JSON file:
[{
"id": 1,
"name": "Salaried"
}, {
"id": 2,
"name": "Apprenticeship"
}]
Chrome enforces stricter web security. If you'd like to allow this in Chrome, you can start Chrome with the following flags: --disable-web-security -–allow-file-access-from-files. Keep in mind that you should not run Chrome with these flags for regular browsing.
Alternatively (perhaps preferably), you could start a local web server. Python makes a good choice for this with it's SimpleHTTPServer module:
$ python -m SimpleHTTPServer 8080
Im assuming you are just opening the index.html directly in your browser and not running a webserver correct? In your console you should be seeing an error like:
"Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource."
Trying running something like http-server and then opening the file.
If you have npm installed you can run:
npm install http-server -g
From the command line in the root of you project run:
http-server
Once finished simply type the following in your browser address bar. Now it works in Chrome.
http://localhost:8080/
Worked on basic routing in angular Js with Code1 mentioned below and getting "XMLHttpRequest cannot load Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https, chrome-extension-resource" error and founded that we must use local web server to resolve the same and downloaded MAMP and kept my html[login.html] in htdocs folder started the server and replaced templateUrl with [localhostURL/AngularJs/login.html'] as mentioned in Code2 and getting error of Error: [$sce:insecurl] exact error are given below, Guide me with any solution to fix the same in Google Chrome...
Code 1
index.html
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body ng-app="plunker">
<div ng-view=""></div>
<script src="angular.min.js"></script>
<script src="angular-route.js"></script>
<script src="app.js"></script>
</body>
</html>
app.js
var app = angular.module('plunker', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/login',{
controller: '',
templateUrl: 'login.html'
}).otherwise({
redirectTo: '/login'
});
});
login.html
Hello from login!
Code2
All other thing are same with changes only in app.js
var app = angular.module('plunker', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/login',{
controller: '',
templateUrl: 'http://localhost:8888/AngularJs/login.html'
}).otherwise({
redirectTo: '/login'
});
});
Error Code1:-
XMLHttpRequest cannot load file://localhost/Users/karthicklove/Documents/Aptana%20Studio%203%20Workspace/Object_Javascript/Angular_Js/Routing/login.html. Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https, chrome-extension-resource.
Error Code2:- [$sce:insecurl] http://errors.angularjs.org/1.2.26/$sce/insecurl?p0=http%3A%2F%2Flocalhost%3A8888%2FAngularJs%2Flogin.html at Error (native)
I got the similar error. I got a solutions for this, we cannot use Routing in AngularJS by keeping it in your file system. (i.e)file:///C:/Users/path/to/file.html?r=4383065' If you run with this URL you will get error. The route provider will use http protocol. So you have to put your code inside the localhost and then run from browser localhost/foldername/index.html . Don't run it from the folder directly
And also change your template URL like this
templateUrl: '/AngularJs/login.html'
If you have doubt post here.
If you are running a page directly from Chrome (you just double clicked on an html file) and your javascript is trying to request some data you will hit this error.
Reason :
$routeProvider uses HTTP service for requesting data and this request cant be sent unless you are using any server like Tomcat.
Solution :
Deploy your app in any server like Tomcat in your machine and open your page through server.
If you think your just playing around with Client-Side coding then better open file in other browsers like Firefox / Safari.
the issue is probably that you are viewing you page through a different port (port 80 is default http port) yet you are accesssing port 8888 so it would see thee this as a cross origin request and block it think it is potentially a XSS attack or similar.
if you are already on the same port, change the template url to
templateUrl: '/AngularJs/login.html'
Issue mentioned here is resolved by making this as an application i.e when i made this html+angular js page to server dependent and run on server the problem is resolved it works fine in google chrome browser...
As other people have said the problem is the $http service from angularjs and you can work around this by hosting a static file web server.
You can do this without much work by using the http-server npm package.
npm install http-server -g
And start your web service like so.
http-server "C:\path\to\project\"
You will see the following output and can browse the app by using one of the displayed urls.
Starting up http-server, serving ./
Available on:
http://192.168.206.1:8080
http://192.168.89.1:8080
http://192.168.7.202:8080
http://127.0.0.1:8080
http-server is a simple, zero-configuration command-line http server. It is powerful enough for production usage, but it's simple and hackable enough to be used for testing, local development, and learning.
Just be aware that both the web server and the browser now caches your requests.
I'm using angular to develop an application. I'm developing off my local file system, on Windows. However, when I enable angular-route.js, whenever I hit index.html with my browser, it instead goes to index.html#/C:/.
My route definition is:
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {templateUrl: 'home.html', controller: 'HomeCtrl'});
}
I think this causes the site to break, because /C:/ doesn't match any angular routes. What's going wrong? How do I fix this?
For routing & ajax (& more) to work properly, run a local development server; avoid use of file:// for development, since browsers have different rules for it.
Tools like yeoman + generator-angular will automatically set up a gruntfile with a server task, which will run a node-connect server to locally serve your files.
You can do this with
python: (3)python -m http.server 8001 (replace http.server with SimpleHttpServer in 2)
node.js + connect
ruby + rack
From the angularjs tutorial (number 5 under "working with the code") - "You need an http server running on your system, but if you don't already have one already installed, you can use node to run scripts\web-server.js, a simple bundled http server."
Response from comments: For phonegap, use the phonegap tools. It does exactly what I said, it runs a local server.
This will work.
angular.module('MainModule', []).config(function($locationProvider, $routeProvider) {
$locationProvider.hashPrefix("!");
$locationProvider.html5Mode(false);
$routeProvider.when('/', {template: './js/templates/home.html', controller:HelloWorldCtrl});
$routeProvider.when('/other', {template: './js/templates/other.html'});
});
In index HTML you need to specify templates:
<script type="text/ng-template" src="./js/templates/home.html"></script>
<script type="text/ng-template" src="./js/templates/other.html"></script>