6

I'm using AngularJs with templating system. I want to add specific inline javascript script to each template adding alert box regards to the selected tab ( Home | List | Settings )

Html renders : but ng-scope is added and nothing alerts when you change of tabs.

<script type="text/javascript" class="ng-scope">alert("home")</script> 

I make the example available here

or here

plunkr example with alert("template1") present into template1.html but renders as

<script type="text/javascript" class="ng-scope">alert("template1")</script> 
3
  • Is that stray closing /script supposed to be there? Commented Nov 11, 2013 at 23:09
  • adding class to script tag, or any other tag won't stop script from running.... is there any text inside script tag? Wouldn't be surprised if it gets stripped out to avoid scripts over writing themselves. jQuery does same thing with their html() method, removes all scriot before DOM insertion Commented Nov 11, 2013 at 23:47
  • I may have the same issue, since my update to angular 1.2, my javascript code isn't loaded anymore with partials template. Commented Nov 12, 2013 at 22:28

2 Answers 2

12

I have improved endorama's solution at github

The same process.

  1. Create the angular-loadscript.js (from the link above)
  2. in your app use 'ngLoadScript' as a resource dependency.

    var app = angular.module('YOUR_APP_NAME', ['ngResource','ngRoute', ...,'ngLoadScript']);

  3. In your partial use 'text/javascript-lazy' as the MIME type.

Everything should work as required:

/*global angular */ (function (ng) { 'use strict'; var app = ng.module('ngLoadScript', []); app.directive('script', function() { return { restrict: 'E', scope: false, link: function(scope, elem, attr) { if (attr.type==='text/javascript-lazy') { var s = document.createElement("script"); s.type = "text/javascript"; var src = elem.attr('src'); if(src!==undefined) { s.src = src; } else { var code = elem.text(); s.text = code; } document.head.appendChild(s); elem.remove(); /*var f = new Function(code); f();*/ } } }; }); }(angular)); 
Sign up to request clarification or add additional context in comments.

3 Comments

I put multiple javascript lazies in the same file, and the load order doesn't jive =(
improved? copy-pasted you mean
How to make it synchronous call?
0

There is a solution by coding a directive :

https://gist.github.com/endorama/7369006

var app = ng.module('ngLoadScript', []); app.directive('script', function() { return { restrict: 'E', scope: false, link: function(scope, elem, attr) { if (attr.type=='text/javascript-lazy') { var code = elem.text(); var f = new Function(code); f(); } } }; }); 

usage in partial :

 <script type="text/javascript-lazy" > alert("lazy loaded"); </script> 

1 Comment

Is there a way to do this but still use the "src" attribute on the script tag?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.