Demo of an AngularJS directive's templateUrl in JsBin - angularjs-directive

I have working code that I want to demo with JsBin but I can't get the AngularJS directive templateUrl to work (it does work with the template value).
http://jsbin.com/guvok/ is trying to reference http://jsbin.com/razit/ but fails.
For the sake of completeness and posterity here's the code:
hello.html
<!DOCTYPE html>
<html ng-app="hello">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
</head>
<body>
<div hello></div>
</body>
</html>
hello.css
.hello__content {
background: #fff;
}
hello.js
var meter = angular.module('hello', [])
.directive( 'hello', function() {
return {
restrict: 'A',
replace: true,
//template: '<p class="hello__content">hello</p>',
templateUrl: 'http://jsbin.com/razit/',
};
});
template.html
<p>hello, world</p>

When I run http://jsbin.com/guvok/, I get the following error in the Javascript console in my browser:
Error: [$sce:insecurl] http://errors.angularjs.org/1.2.19/$sce/insecurl?p0=http%3A%2F%2Fjsbin.com%2Frazit%2F
If you look up "$sce:insecurl", you'll find the AngularJs error reference doc that says,
AngularJS' Strict Contextual Escaping (SCE) mode (enabled by default)
has blocked loading a resource from an insecure URL.
Typically, this would occur if you're attempting to load an Angular
template from an untrusted source. It's also possible that a custom
directive threw this error for a similar reason.
It also offers a few ways to solve the problem, which is essentially a CORS issue.

Put this at the top of your HTML (after the script tag that loads Angular):
<script type="text/ng-template" id="templateURL">
<!-- TEMPLATE MARKUP GOES HERE -->
</script>
Edit: In your case, the ID would be "http://jsbin.com/razit/", that way you wont have to edit your directive. Worst case, change the templateURL to not reference an external jsBin.
Edit #2: Changing the templateUrl to a string value not referencing an external url or with the http protocol, I now see your output in jsBin edit mode.
jsBin here: http://jsbin.com/dutofete/1/

Related

How does AngularJS routing affect simple "scroll to top" page links?

I'm using a HTML anchor tag for a "back to top" link in the footer of my web page:
Back to top
At the top of the page I inserted another anchor tag in the HEAD tag:
<a id="#top"></a>
I've also implemented AngularJS by declaring my app on the HTML tag of index.html:
<html lang="en" ng-app="myApp">
... and I'm using routing as follows:
angular.module('myApp', [
'ui.router'
])
.config(['$stateProvider', '$locationProvider', function($stateProvider, $locationProvider) {
$stateProvider
.state('home', {
url: '/'
});
$locationProvider
.html5Mode({
enabled: true,
requireBase: false
});
}]);
I intend in the future to make the page a full-fledged AngularJS app, but for now all this is a minimal declaration (so controllers, etc., are not included yet).
However, when I add a minimal AngularJS declaration as such, I observe strange behavior when clicking on the "back to top" link in the footer. The first time I click on this link, the page scrolls to the top as intended.
But the second time I click on it, nothing occurs. To sum up, the link doesn't work when clicking on it twice in a row.
Might anyone have an explanation for this behavior? When I remove the Angular code, the link behaves as it should.
Yes if you're using conventional anchor tag with href hash linking, then it'll conflict with routing. In angular there's service called $anchorScroll to do that, so your html should be:
<a ng-click="goTo('top')" class="footer__top">Back to top</a>
And in controller of that view have function goTo as:
$scope.goTo = function(id) {
$location.hash(id);
$anchorScroll();
};
Make sure you've injected $location & $anchorScroll as dependencies inside controller.
Plunker
Now above solution is for having hash linking on same page/route. But i you need such in other route then you can handle that centrally on event of $routeChangeSuccess or $stateChangeSuccess or in recent ui-router version Transition.onSuccess as:
$rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {
$location.hash($routeParams.scrollTo);
$anchorScroll();
});
And in some other view have anchor tags like:
route1 / Foo
route2 / Bar
Plunker

page doesn't work after moving files (and changing the src)

There are similar questions like mine, but they couldn't help me out.
html:
<!DOCTYPE html>
<html>
<head>
<title>Test-Site</title>
<script src="scripts/angular.js"></script>
<script src="scripts/angular-route.js"></script>
<script src="~/App_Data/mainApp.js"></script>
<script src="~/Controllers/testController.js"></script>
</head>
<body>
<div ng-app="~/App_Data/mainApp" ng- controller="~/Controllers/testController">
Write your Name:<input type="text" ng-model="name.firstName" />
Your Name: {{name.firstName}}
</div>
main.app.js:
var mainApp = angular.module("mainApp", []);
test.controller.js:
mainApp.controller("testController", function ($scope) {
$scope.name = { firstName: "Peter" };
});
Chrome console gives me following errors:
Test.html:8 GET http://localhost:55835/~/Controllers/testController.js
Test.html:7 GET http://localhost:55835/~/App_Data/mainApp.js
angular.js:63 Uncaught Error: [$injector:modulerr] Failed to instantiate module ~/App_Data/mainApp due to:
Error: [$injector:nomod] Module '~/App_Data/mainApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
Everything was fine, until I moved the js-files into their folders.
What am I doing wrong?
You are using the server side path ~/ in a client side page. You cannot use the server side path in this way. You need to provide the full path from the root of the site to your files; most likely, just removing the ~/ will be enough.
As a side note, normally the App_Data folder is for things like Database files and other server resources; it seems an odd place to put your mainApp.js file.

404 issue with ng-include inside of ng-view

I've searched everywhere for the answer but unfortunately I didn't find anything.
I have a working Angular application that looks like this:
...
<div class="container" ng-app="myApp">
<div class="page-title">
<h1>
Hello
</h1>
</div>
<div ng-view></div>
</div>
...
I'm working with ngRoute to load html partials into the ng-view div.
my JS:
var myApp = angular.module('myApp', [
'ngRoute',
'myControllers'
]);
myApp.config(['$routeProvider', '$httpProvider',
function($routeProvider, $httpProvider) {
$routeProvider.
when('/step1', {
templateUrl: 'template1.html',
controller: 'Step1Controller'
}).
when('/step2', {
templateUrl: 'template2.html',
controller: 'Step2Controller'
}).
when('/step3', {
templateUrl: 'template3.html',
controller: 'Step3Controller'
}).
otherwise({
redirectTo: '/step1'
});
}]);
Up to here, everything works as a charm. I already completed pretty much everything I needed (a multi stepped wizard).
On the last step, I needed to use <script type="text/ng-template" id="specialTemplate.html"></script> to generate some special template (a tree)
So, in my last step page partial (template3.html) I did the following:
<ul>
<li ng-repeat="item in [1,2,3]" ng-include="'specialTemplate.html'"></li>
</ul>
<script type="text/ng-template" id="specialTemplate.html">
Test
</script>
Here I got stuck. I'm getting 404 errors on console (he tries to look up specialTemplate.html in the same directory my browser's url points to), and the template does not load.
When I made some tests I saw that if the ng-include is outside of the ng-view, but inside a clean ng-controller separated from my current working flow, It does find and load the template, but this doesn't help me because I must render the tree within my working steps flow.
Is it impossible to load a <script> based template inside ng-view?
Thanks in advance for your help.
EDIT:
Version: AngularJS v1.3.0-beta.3
it could be that when you try to grab specialTemplate.html from within ngView it changes the url being pointed to by ngInclude. Try hardcoding the path to specialTemplate.html. Or you could try putting your script inside the li because it might also be a scope issue.
If you are testing in a local Windows system, then not serving up your pages from http-server might be the problem.
As a fix, install http-server globally using the commnd:
npm install -g http-server
and remember to use a sudo for Linux system.
Once the server installed, start the server using the command:
http-server
Now, go to http://127.0.0.1:8080/ in your browser and navigate to your desired page.

Offline mobile application - should i be able to read in a localally stored JSON file?

My question is similar to the one here Trying to parse JSON file with jQuery but i don't seem to be able to adapt it.
I want to create an offline mobile app mainly using HTML5, CSS and JavaScript/Jquery
All the files in the app will be cashed I hope when I've it working
I had thought to created a JSON file containing some data about computer labs - eg open hours capasity that type of thing
{ "name":"Boole basement",
"location":"Main Campus",
"staffed":"Yes"}
And then read in the localy stored JSON file - parse it or whatever and then display each object in a new div. Initially I was just trying to get the data into one div. heck if I could get the contents of the JSON file to display I'd be delighted!
My HTML file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>test</title>
<script src="jquery-1.6.2.min.js"></script>
<script>
/* <![CDATA[ */
$(document).ready(function(){
var test =" ";
var filename = "test.json";
$.getJSON(filename, function(json){
$.each(json.labs, function(i, lab){
test = lab.name;
test+=" "+lab.location;
$('#space').append(test);
alert("Hi");
});
});
});
/* ]]> */
</script>
</head>
<body>
<h2>available labs:</h2>
<div id="space">some text</div>
</body>
</html>
PS Is what I've discribed even possible...
What you have described is entirely possible, yes. But your code needs work:
For example, your selector for space is incorrect (it's an ID in your mark-up, but you're using a class selector in your jQuery code).
(EDIT OK, I see you've edited your example code now).

Include html file into another html file

Can someone guide me how to include html file with an html file. I have been trying to embed my file within object tags but to no avail.
Thanks!
You can use the iframe tag.
Another option is to used Server Side inclusion using SHTML, this require that the web server support it, see Server Side Includes
You are quite limited in HTML. You can use iframe tag but it's the same type of embedding as embedding of flash in html pages.
OT: It would be quite easy in PHP. Can you use it? Or do you need static web page?
Can you perhaps use Javascript to dynamically load it in?
You can have it loaded via JQuery as shown here: Include another HTML file in a HTML file
a.html:
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function{
$("#includedContent").load("b.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
b.html:
<p> This is my include file </p>
May be this help:
Inside js/utils.js define functions:
function loadFileSync(fileName) {
var req = new XMLHttpRequest();
req.open('GET', fileName, false);
req.send(null);
if (req.status === 200) {
//console.log(req.responseText);
return req.responseText
} else
return "ERROR!!!"
}
function includeFile(fileName) {
document.write(loadFileSync(fileName))
}
And in main html file add this:
<script src="js/utils.js"></script>
<script> includeFile("navigation.html") </script>