Javascript ads in Angular templates - javascript

I'm trying to render a Javascript ad in my Angular template but it will not show up. I've found some solutions when they append the Javascript to the head tag but I want the ad to be placed in my Html (inside body).
Here is a Plunker: https://plnkr.co/edit/WHhQ95gS5HKSphmmirio
Here is a simple plain Html example that works.
<html>
<head>
</head>
<body>
<div class="ad">
<script src="http://media.affiliatelounge.com/data/nordicbet/ad_js/display_88.js?ad=ad_793270_88.html&size=300x250&clicktag=http://record.affiliatelounge.com/_sVuSoFFh4LK58VwA2IUESrKVVrME-Gsw/1&media=108786&campaign=1"></script>
</div>
</body>
</html>
But if I add the div inside an Angular template it will not render and the console says nothing.
I have some ads up and running here (http://www.odds.nu/erbjudanden), but they are either .gif or iframes. I want to be able to show Javascript ads instead. They are added to the Html but are not rendered (placed in the bottom of the page).
Can $sce or $compile help somehow?
My index.html
<div data-ng-view="" class="mainView"></div>
My app.js
$routeProvider.when("/erbjudanden", {
controller: "offerController",
templateUrl: "/app/templates/offers.html"
});
My offers.html
<div class="ad">
<script src="http://media.affiliatelounge.com/data/nordicbet/ad_js/display_88.js?ad=ad_793270_88.html&size=300x250&clicktag=http://record.affiliatelounge.com/_sVuSoFFh4LK58VwA2IUESrKVVrME-Gsw/1&media=108786&campaign=1"></script>
</div>
Any solution?

If you had inspected result of that url request(make sure adBlock is off)
https://wlbetclic.adsrv.eacdn.com/S.ashx?btag=a_17172b_14837c_&affid=12824&siteid=17172&adid=14837&c=
You will see the actual result
document.write('<script type="text/javascript" src="//wlbetclic.eacdn.com/TrafficOpt/s.5.4.min.js?t=1"></script>');
document.write('<script type="text/javascript" src="//wlbetclic.eacdn.com/wlbetclic/img/js/Affiliate_12824.js?t=20160224"></script>');
//other lines omitted for brevity
So this file is executing document.write which obviously will not work in angular, just because they are totally different (even though you could trigger digest cycle somehow, you still don't have access to modify that script file, as it's generated by 3rd party server and has own variables)
What i would do is - make a page like ad.html, just like index.html or 404.html, then request this file from angular (not as template, but like a view file) as an iframe src with custom attributes
And i would use custom DOM element, and populate contents with jQuery, or with angular, look at jQuery sample below
Also i would need krux/postscribe plugin, because you cannot use document.write in async html files
<!-- create multiple holders -->
<ad-holder url="https://wlbetclic.adsrv.eacdn.com/S.ashx?btag=a_17172b_14837c_&affid=12824&siteid=17172&adid=14837&c="></ad-holder>
<div class="black-widow">
<!-- with size attributes -->
<ad-holder url="http://google.com" width="100" height="40"></ad-holder>
</div>
<!-- jQuery population with iframe -->
<script>
//get all custom elements
$('ad-holder').each(function(){
//create iframe placeholder
var $iframe = $(document.createElement('iframe'));
//get url of custom element
var url = $(this).attr('url');
//request ad.html file with params, currently it's url param
$iframe.attr('src', 'ad.html?url=' + url);
//some stylings acceptable here
$iframe.width('100px');
//or get styles from custom-element
var heightValue = $(this).attr('height');
$iframe.height(heightValue || '50px');
//rebuild custom element with iframe
$(this).append($iframe);
});
</script>
<!-- angular populate with iframe directive -->
<scrip>
angular.module('app', []).directive('adHolder', function(){
return {
restrict: 'E',
scope: { url: '#' },
//you could also execute in compile-phase
link: function(scope, element, attribute){
var $iframe = angular.element(document.createElement('iframe'));
$iframe.attr('src', 'ad.html?url=' + scope.url);
element.html($iframe);
}
}
});
</script>
And ad.html would look like
<body>
<div id="ad"></div>
<script>
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
//for the sake of simplicity we expect only 1 param (url)
return query.replace('url=', '');
}
var adUrl = getQueryVariable('url');
if (adUrl)
postscribe('#ad', '<script src="' + adUrl + '"><\/script>');
else {
var $h1 = $(document.createElement('h1'));
$h1.text('No ad available');
$(document.body).append($h1);
}
</script>
</body>
The best part of this solution is that you can reuse same custom-element with different url attribute for any other ads
Checkout jQuery real working demo
Although this demo heavily uses jQuery, it's easy to tweak for angular version, which i would suggest you to implement as homework =)

Short answer:
Angular does not perform compilation of Javascript in HTML templates. You either put the HTML manually in the page (instead of loading as template) or have another way to call it.
You can read more here

Related

How to use string resources in html files [duplicate]

I have 2 HTML files, suppose a.html and b.html. In a.html I want to include b.html.
In JSF I can do it like that:
<ui:include src="b.xhtml" />
It means that inside a.xhtml file, I can include b.xhtml.
How can we do it in *.html file?
In my opinion the best solution uses jQuery:
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>
This method is a simple and clean solution to my problem.
The jQuery .load() documentation is here.
Expanding lolo's answer, here is a little more automation if you have to include a lot of files. Use this JS code:
$(function () {
var includes = $('[data-include]')
$.each(includes, function () {
var file = 'views/' + $(this).data('include') + '.html'
$(this).load(file)
})
})
And then to include something in the html:
<div data-include="header"></div>
<div data-include="footer"></div>
Which would include the file views/header.html and views/footer.html.
My solution is similar to the one of lolo above. However, I insert the HTML code via JavaScript's document.write instead of using jQuery:
a.html:
<html>
<body>
<h1>Put your HTML content before insertion of b.js.</h1>
...
<script src="b.js"></script>
...
<p>And whatever content you want afterwards.</p>
</body>
</html>
b.js:
document.write('\
\
<h1>Add your HTML code here</h1>\
\
<p>Notice however, that you have to escape LF's with a '\', just like\
demonstrated in this code listing.\
</p>\
\
');
The reason for me against using jQuery is that jQuery.js is ~90kb in size, and I want to keep the amount of data to load as small as possible.
In order to get the properly escaped JavaScript file without much work, you can use the following sed command:
sed 's/\\/\\\\/g;s/^.*$/&\\/g;s/'\''/\\'\''/g' b.html > escapedB.html
Or just use the following handy bash script published as a Gist on Github, that automates all necessary work, converting b.html to b.js:
https://gist.github.com/Tafkadasoh/334881e18cbb7fc2a5c033bfa03f6ee6
Credits to Greg Minshall for the improved sed command that also escapes back slashes and single quotes, which my original sed command did not consider.
Alternatively for browsers that support template literals the following also works:
b.js:
document.write(`
<h1>Add your HTML code here</h1>
<p>Notice, you do not have to escape LF's with a '\',
like demonstrated in the above code listing.
</p>
`);
Checkout HTML5 imports via Html5rocks tutorial
and at polymer-project
For example:
<head>
<link rel="import" href="/path/to/imports/stuff.html">
</head>
Shameless plug of a library that I wrote the solve this.
https://github.com/LexmarkWeb/csi.js
<div data-include="/path/to/include.html"></div>
The above will take the contents of /path/to/include.html and replace the div with it.
No need for scripts. No need to do any fancy stuff server-side (tho that would probably be a better option)
<iframe src="/path/to/file.html" seamless></iframe>
Since old browsers don't support seamless, you should add some css to fix it:
iframe[seamless] {
border: none;
}
Keep in mind that for browsers that don't support seamless, if you click a link in the iframe it will make the frame go to that url, not the whole window. A way to get around that is to have all links have target="_parent", tho the browser support is "good enough".
A simple server side include directive to include another file found in the same folder looks like this:
<!--#include virtual="a.html" -->
Also you can try:
<!--#include file="a.html" -->
A very old solution I did met my needs back then, but here's how to do it standards-compliant code:
<!--[if IE]>
<object classid="clsid:25336920-03F9-11CF-8FD0-00AA00686F13" data="some.html">
<p>backup content</p>
</object>
<![endif]-->
<!--[if !IE]> <-->
<object type="text/html" data="some.html">
<p>backup content</p>
</object>
<!--> <![endif]-->
Following works if html content from some file needs to be included:
For instance, the following line will include the contents of piece_to_include.html at the location where the OBJECT definition occurs.
...text before...
<OBJECT data="file_to_include.html">
Warning: file_to_include.html could not be included.
</OBJECT>
...text after...
Reference: http://www.w3.org/TR/WD-html40-970708/struct/includes.html#h-7.7.4
Here is my inline solution:
(() => {
const includes = document.getElementsByTagName('include');
[].forEach.call(includes, i => {
let filePath = i.getAttribute('src');
fetch(filePath).then(file => {
file.text().then(content => {
i.insertAdjacentHTML('afterend', content);
i.remove();
});
});
});
})();
<p>FOO</p>
<include src="a.html">Loading...</include>
<p>BAR</p>
<include src="b.html">Loading...</include>
<p>TEE</p>
In w3.js include works like this:
<body>
<div w3-include-HTML="h1.html"></div>
<div w3-include-HTML="content.html"></div>
<script>w3.includeHTML();</script>
</body>
For proper description look into this: https://www.w3schools.com/howto/howto_html_include.asp
As an alternative, if you have access to the .htaccess file on your server, you can add a simple directive that will allow php to be interpreted on files ending in .html extension.
RemoveHandler .html
AddType application/x-httpd-php .php .html
Now you can use a simple php script to include other files such as:
<?php include('b.html'); ?>
This is what helped me. For adding a block of html code from b.html to a.html, this should go into the head tag of a.html:
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
Then in the body tag, a container is made with an unique id and a javascript block to load the b.html into the container, as follows:
<div id="b-placeholder">
</div>
<script>
$(function(){
$("#b-placeholder").load("b.html");
});
</script>
I know this is a very old post, so some methods were not available back then.
But here is my very simple take on it (based on Lolo's answer).
It relies on the HTML5 data-* attributes and therefore is very generic in that is uses jQuery's for-each function to get every .class matching "load-html" and uses its respective 'data-source' attribute to load the content:
<div class="container-fluid">
<div class="load-html" id="NavigationMenu" data-source="header.html"></div>
<div class="load-html" id="MainBody" data-source="body.html"></div>
<div class="load-html" id="Footer" data-source="footer.html"></div>
</div>
<script src="js/jquery.min.js"></script>
<script>
$(function () {
$(".load-html").each(function () {
$(this).load(this.dataset.source);
});
});
</script>
Most of the solutions works but they have issue with jquery:
The issue is following code $(document).ready(function () { alert($("#includedContent").text()); } alerts nothing instead of alerting included content.
I write the below code, in my solution you can access to included content in $(document).ready function:
(The key is loading included content synchronously).
index.htm:
<html>
<head>
<script src="jquery.js"></script>
<script>
(function ($) {
$.include = function (url) {
$.ajax({
url: url,
async: false,
success: function (result) {
document.write(result);
}
});
};
}(jQuery));
</script>
<script>
$(document).ready(function () {
alert($("#test").text());
});
</script>
</head>
<body>
<script>$.include("include.inc");</script>
</body>
</html>
include.inc:
<div id="test">
There is no issue between this solution and jquery.
</div>
jquery include plugin on github
You can use a polyfill of HTML Imports (https://www.html5rocks.com/en/tutorials/webcomponents/imports/), or that simplified solution
https://github.com/dsheiko/html-import
For example, on the page you import HTML block like that:
<link rel="html-import" href="./some-path/block.html" >
The block may have imports of its own:
<link rel="html-import" href="./some-other-path/other-block.html" >
The importer replaces the directive with the loaded HTML pretty much like SSI
These directives will be served automatically as soon as you load this small JavaScript:
<script async src="./src/html-import.js"></script>
It will process the imports when DOM is ready automatically. Besides, it exposes an API that you can use to run manually, to get logs and so on. Enjoy :)
Here's my approach using Fetch API and async function
<div class="js-component" data-name="header" data-ext="html"></div>
<div class="js-component" data-name="footer" data-ext="html"></div>
<script>
const components = document.querySelectorAll('.js-component')
const loadComponent = async c => {
const { name, ext } = c.dataset
const response = await fetch(`${name}.${ext}`)
const html = await response.text()
c.innerHTML = html
}
[...components].forEach(loadComponent)
</script>
To insert contents of the named file:
<!--#include virtual="filename.htm"-->
Another approach using Fetch API with Promise
<html>
<body>
<div class="root" data-content="partial.html">
<script>
const root = document.querySelector('.root')
const link = root.dataset.content;
fetch(link)
.then(function (response) {
return response.text();
})
.then(function (html) {
root.innerHTML = html;
});
</script>
</body>
</html>
Did you try a iFrame injection?
It injects the iFrame in the document and deletes itself (it is supposed to be then in the HTML DOM)
<iframe src="header.html" onload="this.before((this.contentDocument.body||this.contentDocument).children[0]);this.remove()"></iframe>
Regards
The Athari´s answer (the first!) was too much conclusive! Very Good!
But if you would like to pass the name of the page to be included as URL parameter, this post has a very nice solution to be used combined with:
http://www.jquerybyexample.net/2012/06/get-url-parameters-using-jquery.html
So it becomes something like this:
Your URL:
www.yoursite.com/a.html?p=b.html
The a.html code now becomes:
<html>
<head>
<script src="jquery.js"></script>
<script>
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}​
$(function(){
var pinc = GetURLParameter('p');
$("#includedContent").load(pinc);
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
It worked very well for me!
I hope have helped :)
html5rocks.com has a very good tutorial on this stuff, and this might be a little late, but I myself didn't know this existed. w3schools also has a way to do this using their new library called w3.js. The thing is, this requires the use of a web server and and HTTPRequest object. You can't actually load these locally and test them on your machine. What you can do though, is use polyfills provided on the html5rocks link at the top, or follow their tutorial. With a little JS magic, you can do something like this:
var link = document.createElement('link');
if('import' in link){
//Run import code
link.setAttribute('rel','import');
link.setAttribute('href',importPath);
document.getElementsByTagName('head')[0].appendChild(link);
//Create a phantom element to append the import document text to
link = document.querySelector('link[rel="import"]');
var docText = document.createElement('div');
docText.innerHTML = link.import;
element.appendChild(docText.cloneNode(true));
} else {
//Imports aren't supported, so call polyfill
importPolyfill(importPath);
}
This will make the link (Can change to be the wanted link element if already set), set the import (unless you already have it), and then append it. It will then from there take that and parse the file in HTML, and then append it to the desired element under a div. This can all be changed to fit your needs from the appending element to the link you are using. I hope this helped, it may irrelevant now if newer, faster ways have come out without using libraries and frameworks such as jQuery or W3.js.
UPDATE: This will throw an error saying that the local import has been blocked by CORS policy. Might need access to the deep web to be able to use this because of the properties of the deep web. (Meaning no practical use)
Use includeHTML (smallest js-lib: ~150 lines)
Loading HTML parts via HTML tag (pure js)
Supported load: async/sync, any deep recursive includes
Supported protocols: http://, https://, file:///
Supported browsers: IE 9+, FF, Chrome (and may be other)
USAGE:
1.Insert includeHTML into head section (or before body close tag) in HTML file:
<script src="js/includeHTML.js"></script>
2.Anywhere use includeHTML as HTML tag:
<div data-src="header.html"></div>
There is no direct HTML solution for the task for now. Even HTML Imports (which is permanently in draft) will not do the thing, because Import != Include and some JS magic will be required anyway.
I recently wrote a VanillaJS script that is just for inclusion HTML into HTML, without any complications.
Just place in your a.html
<link data-wi-src="b.html" />
<!-- ... and somewhere below is ref to the script ... -->
<script src="wm-html-include.js"> </script>
It is open-source and may give an idea (I hope)
You can do that with JavaScript's library jQuery like this:
HTML:
<div class="banner" title="banner.html"></div>
JS:
$(".banner").each(function(){
var inc=$(this);
$.get(inc.attr("title"), function(data){
inc.replaceWith(data);
});
});
Please note that banner.html should be located under the same domain your other pages are in otherwise your webpages will refuse the banner.html file due to Cross-Origin Resource Sharing policies.
Also, please note that if you load your content with JavaScript, Google will not be able to index it so it's not exactly a good method for SEO reasons.
Web Components
I create following web-component similar to JSF
<ui-include src="b.xhtml"><ui-include>
You can use it as regular html tag inside your pages (after including snippet js code)
customElements.define('ui-include', class extends HTMLElement {
async connectedCallback() {
let src = this.getAttribute('src');
this.innerHTML = await (await fetch(src)).text();;
}
})
ui-include { margin: 20px } /* example CSS */
<ui-include src="https://cors-anywhere.herokuapp.com/https://example.com/index.html"></ui-include>
<div>My page data... - in this snippet styles overlaps...</div>
<ui-include src="https://cors-anywhere.herokuapp.com/https://www.w3.org/index.html"></ui-include>
None of these solutions suit my needs. I was looking for something more PHP-like. This solution is quite easy and efficient, in my opinion.
include.js ->
void function(script) {
const { searchParams } = new URL(script.src);
fetch(searchParams.get('src')).then(r => r.text()).then(content => {
script.outerHTML = content;
});
}(document.currentScript);
index.html ->
<script src="/include.js?src=/header.html">
<main>
Hello World!
</main>
<script src="/include.js?src=/footer.html">
Simple tweaks can be made to create include_once, require, and require_once, which may all be useful depending on what you're doing. Here's a brief example of what that might look like.
include_once ->
var includedCache = includedCache || new Set();
void function(script) {
const { searchParams } = new URL(script.src);
const filePath = searchParams.get('src');
if (!includedCache.has(filePath)) {
fetch(filePath).then(r => r.text()).then(content => {
includedCache.add(filePath);
script.outerHTML = content;
});
}
}(document.currentScript);
Hope it helps!
Here is a great article, You can implement common library and just use below code to import any HTML files in one line.
<head>
<link rel="import" href="warnings.html">
</head>
You can also try Google Polymer
To get Solution working you need to include the file csi.min.js, which you can locate here.
As per the example shown on GitHub, to use this library you must include the file csi.js in your page header, then you need to add the data-include attribute with its value set to the file you want to include, on the container element.
Hide Copy Code
<html>
<head>
<script src="csi.js"></script>
</head>
<body>
<div data-include="Test.html"></div>
</body>
</html>
... hope it helps.
There are several types of answers here, but I never found the oldest tool in the use here:
"And all the other answers didn't work for me."
<html>
<head>
<title>pagetitle</title>
</head>
<frameset rows="*" framespacing="0" border="0" frameborder="no" frameborder="0">
<frame name="includeName" src="yourfileinclude.html" marginwidth="0" marginheight="0" scrolling="no" frameborder="0">
</frameset>
</html>

JS source not visible in Chrome/Firefox debuggers, but correctly loaded in the page

I have a web page which does navigation using templates and filling / showing them depending of user interactions.
It works quite well, but the templates contains some JS included with them. This JS code is correctly loaded (in the example below, it provides an alert saying "Hi") when the page is just loaded. However, I don't see the code within the debugger console, either in Chrome or Firefox.
I've provided a minimal example below, where I see in the console > Source, under localhost, only my HTML page and jquery.min.js in the asset/js sub-folder.
Here is my HTML :
<script src="assets/js/jquery.min.js"></script>
<template id="my_screen">
Hello
<script type="application/javascript" src="assets/js/testouille.js"></script>
</template>
<section class="container">
<div class="my_screen hide"></div>
</section>
<script type="application/javascript">
function useTemplate(elem) {
var myTemplate = $('#' + elem),
normalContent = $('.' + elem),
clonedTemplate = myTemplate.html();
normalContent.empty();
normalContent.append(clonedTemplate);
}
$(document).ready(function() {
useTemplate('my_screen');
}
)
</script>
And here is my Javascript :
alert("Hi");
Any idea?
Since testouille.js is in a <template>, it's not loaded automatically by the browser when the page is loaded.
When you clone the template and append it to a regular DIV, jQuery emulates loading the file using $.getScript(). In the Chrome debugger, code that's loaded this way will be shown in a VM:#### filename (where #### is an arbitrary number) in Sources, rather than with its actual filename.
You can make the debugger give this a filename by putting the following comment in testouille.js:
//# sourceURL=testouille.js

Loading external scripts within angular html views

I have signed up to a paid version of Polldaddy and was provided this script tag (minus the proper id).
<script type="text/javascript" charset="utf-8" src="http://static.polldaddy.com/p/0000000.js"></script>
This script has to be loaded within a div in a view of mine - and it is not working. Does angular have an issue with loading scripts within a view? Is it possible? If so, could you help me understand how to do it please?
Let me know if you need more info.
Thanks
You can't load a script inside an Angular app due the Angular script directive, so you need to create your own directive.
Something like this:
function polldaddy() {
var injectScript = function(element) {
var scriptTag = angular.element(document.createElement('script'));
scriptTag.attr('charset', 'utf-8');
scriptTag.attr('src', 'http://static.polldaddy.com/p/0000000.js');
element.append(scriptTag);
};
return {
link: function(scope, element) {
injectScript(element);
}
};
}
angular
.module('myApp')
.directive('polldaddy', polldaddy);
and then in your HTML:
<div polldaddy></div>

KnockoutJS with Sammy.js SPA suggestion

I am building a SPA app with the following structure:
<body>
<!-- Main Container for our application -->
<div id="main">
</div>
<!-- End Main Container -->
<!-- Vendor Libraries -->
<script src="js/vendor/jquery/jquery-1.11.0.min.js"></script>
<script src="js/vendor/knockout/knockout-3.1.0.js"></script>
<script src="js/vendor/sammy/sammy-latest.min.js"></script>
<!-- Models -->
<script src="js/models/model1.js"></script>
<!-- ViewModels -->
<script src="js/viewmodels/viewModel1.js"></script>
<script src="js/viewmodels/viewModel2.js"></script>
<!-- App scripts -->
<script src="js/routes.js"></script>
<script src="js/app.js"></script>
</body>
The html file has a div which will hold the html for each respective page handled by Sammy.js wit the following code:
Sammy('#main', function() {
this.get('#/', function(context) {
context.$element().load('views/main1.html', function() {
ko.applyBindings(new ViewModel1(), $("#home")[0]);
});
});
this.get('#/text', function(context) {
context.$element().load('views/text.html', function() {
ko.applyBindings(new ViewModel2(), $("#home")[0]);
});
});
this.get('', function(context) {
this.redirect('#/');
});
}).run();
Each time I am loading the markup found in each html file and then apply my viewmodel.
My questions are:
Can you suggest any other possible way to load the markup apart from using jquery load().
Are my old bindings being disposed each time a new route is being called?
1: This question is very 'open'. There are tons of way to do this that aren't jquery.load. But the real question is: do you NEED another way? Do you need some form of control that $.load isn't giving you?
If you do, consider switching to jquery.get or jquery.ajax, and handle the request yourself. At the bottom of this post is an example.
2: No, because you keep applying the bindings to the same element. What you instead want to do is apply bindings to the first element WITHIN the container with id 'home'. Then, when you switch views, you want to do ko.removeNode on the view that you're removing. Below is a code example that illustrates how you can gain some more control over the process and clean up your bindings behind you.
function loadView(url, viewModel) {
$.get(url, function (response) {
var $container = $('#home'),
$view = $container.find('.view'),
$newView = $('<div>').addClass('view').html(response);
if ($view.length) {
ko.removeNode($view[0]); // Clean up previous view
}
$container.append($newView);
ko.applyBindings(viewModel, $newView[0]);
});
}
this.get('#/', function(context) {
loadView('views/main1.html', new ViewModel1());
});
this.get('#/', function(context) {
loadView('views/text.html', new ViewModel2());
});
What I did in this example is using jquery.get so we gain control over the whole process of loading and displaying the HTML. I then refactored part of the logic out into a separate function that is generic enough to use on every view you have.
When a view is retrieved I store it in an element with class 'view'. The bindings are applied to this element and it is stored in your container element. When switching views I clean up and remove the old view before the new view is added to the DOM.
This is just the beginning: In the loadView function, you can now try to call generic methods that you can implement on your viewmodels, such as 'activate' and 'deactivate'. You can also show a spinner instead of a view when a new view is being retrieved, etc.

angular load template from url and compile inside div

As I'm new to Angular JS I was wondering how could I load an external template and compile it with some data into the targeted div.
For instance I have this template :
<script type="text/ng-template">
<img src="{{Thumb}}" />
<script>
The div that is supposed to contain the template :
<div data-ng-controller=" ... "></div>
The template is located somewhere in a folder /templates/test.php. Is there a build in way of doing the template loading like a directive would do and compile it against some data that would replace the key {{Thumb}} ( and many others of course ) ?
EDIT : What if I use $routes and load a template when I'm in the root of the website ? How could that be achieved ?
Using $templateRequest, you can load a template by it’s URL without having to embed it into your HTML page. If the template is already loaded, it will be taken from the cache.
app.controller('testCtrl', function($scope, $templateRequest, $sce, $compile){
// Make sure that no bad URLs are fetched. If you have a static string like in this
// example, you might as well omit the $sce call.
var templateUrl = $sce.getTrustedResourceUrl('nameOfTemplate.html');
$templateRequest(templateUrl).then(function(template) {
// template is the HTML template as a string
// Let's put it into an HTML element and parse any directives and expressions
// in the code. (Note: This is just an example, modifying the DOM from within
// a controller is considered bad style.)
$compile($("#my-element").html(template).contents())($scope);
}, function() {
// An error has occurred here
});
});
Be aware that this is the manual way to do it, and whereas in most cases the preferable way would be to define a directive that fetches the template using the templateUrl property.
in Angular there's 2 ways of using template (at least 2 ways that i know about):
the first using an inline template (in the same file) with this syntax:
<script type="text/ng-template">
<img ng-src="{{thumb}}">
</script>
the second one (what you want) is external template:
<img ng-src="{{thumb}}">
so what you need to do is to remove the script part from your template and then use the ng-include in the wanted div like this:
<div ng-include="'templates/test.php'"></div>
need to have double quotes and single quotes to work.
Hope this helps.
Let's say I have this index.html:
<!doctype html> <html lang="en" ng-app="myApp">
<body>
<script src="tpl/ng.menu.tpl" type="text/ng-template"></script>
<mainmenu></mainmenu>
<script src="lib/angular/angular.js"></script>
<script src="js/directives.js"></script>
</body>
</html>
And I have a template file "tpl/ng.menu.tpl" with only these 4 lines:
<ul class="menu">
<li>view1</li>
<li>view2</li>
</ul>
My directives mapping "js/directives.js":
angular.module('myApp',['myApp.directives']);
var myModule = angular.module('myApp.directives', []);
myModule.directive('mainmenu', function() {
return {
restrict:'E',
replace:true,
templateUrl:'tpl/ng.menu.tpl'
}
});

Categories

Resources