Why ng-scope is added to javascript inline of my partial view and makes alert not working?

橙三吉。 提交于 2019-12-17 09:48:17

问题


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 :

http://bit.ly/HWcN1H

or here

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

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

回答1:


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));



回答2:


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>


来源:https://stackoverflow.com/questions/19917774/why-ng-scope-is-added-to-javascript-inline-of-my-partial-view-and-makes-alert-no

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!