如何使用AngularJS加载非角度JavaScript文件?

Yab*_*rgo 16 javascript lazy-loading angularjs

是否可以从Angular Controller加载普通的旧JS或AMD模块?我之前使用过RequireJS.

我之前在一个相当大的项目上使用过AngularJS和RequireJS.我正在开发一个基于MEAN Stack种子的新项目,这不使用requireJS.

我不是很清楚,但Angular有一个加载模块的系统 - 我可以从我的角度控制器中加载一段特定的javascript吗?

有没有办法修改我的module()声明以包含其他常规javascript文件?

谢谢!

编辑:为了对我正在做的事情有一点了解,我有一个编辑几种不同形式的页面.其中每个都作为"表单"保存到我的数据库中.根据表单的类型,不同的字典值将映射到不同子视图中的不同字段.我的一些表格有例如下拉列表或输入列表.这些是不同的,但关于'表单'的其他所有内容都是以通用方式处理的.

所以我有这个单一的表单控制器来处理一堆不同的形式,我对结果非常满意.主要问题来自于每个表单都有一组单独的数据,我希望避免加载,除非我需要.

我可以通过检查驱动我的ng-include(加载子表单)的下拉列表来检查我正在加载哪个表单.

在短期内,我刚刚加载了所有内容并在我的范围内创建了名称空间来区分.

例如$ scope.form1和$ scope.form2,用于特定表单的数据/规则.我很快就不会加载我不需要的js.

编辑2: http ://jsfiddle.net/HB7LU/1320/

function MyCtrl($scope) {       
    $scope.doSomething = function()
    {
     //I'm used to wrapping with e.g require('jquery..... here, can I do the same thing with angular?   
        alert(" I need to run a jquery function here...");
        var xml = $(someblock);
    };
}
Run Code Online (Sandbox Code Playgroud)

我已经准备好了我正在谈论的内容.我想根据控制器中的某些路径加载任意JS,并且只在我需要时才加载.

基本上我有一些更大的命名空间我想加载,这取决于所选择的众多选项中的一个,并且加载它们将是昂贵的.

m59*_*m59 19

好吧,我评论了我的代码,以便它解释一切.如果您有任何其他问题,请告诉我.这是问题的解决方案,正如您的评论中进一步解释的那样.现场演示(点击).

标记:

<!DOCTYPE html>
<html ng-app="myApp" ng-controller="myCtrl">
<head>
</head>
<body>

  <button ng-click="load()">Load Foo</button>
  <!-- I'm using this to bootstrap the lazy loaded script -->
  <section ng-repeat="item in loaded" lazy="item"></section>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>  
<script src="script.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

JavaScript的:

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
  //array of things to load
  $scope.lazyThings = [
    {directive:'my-foo-directive', file:'foo.js'}  
  ];
  $scope.loaded = [];
  $scope.load = function() {
    var loadIndex = $scope.loaded.length;
    if ($scope.lazyThings[loadIndex]) {
      $scope.loaded.push($scope.lazyThings[loadIndex]);
    }
  }
});

app.factory('myService', function($http) {
  return {
    getJs: function(path) {

      return $http.get(path).then(function(response) {
        deferred.resolve(response.data);
      });

    }
  }
});

//this adds an attribute to kick off the directive 
//for whatever script was lazy loaded
app.directive('lazy', function($compile, $q, myService) {
  var directiveReturn = {
    restrict: 'A',
    scope: {
      lazy: '='
    },
    link: function(scope, element) {
      myService.getJs(scope.lazy.file).then(function(data) {
        return addScript(scope.lazy.file, data, scope);
      }).then(function() {
        var $span = angular.element('<span></span>').attr(scope.lazy.directive, '');
        $compile($span)(scope);
        element.append($span);
      });
    }
  }

  var scriptPromises = {};
  function addScript(file, js, scope) {
    if (!scriptPromises[file]) { //if this controller hasn't already been loaded
      var deferred = $q.defer();
      //cache promise)
      scriptPromises[file] = deferred.promise;

      //inject js into a script tag
      var script = document.createElement('script');
      script.src = 'data:text/javascript,' + encodeURI(js);
      script.onload = function() {
        //now the script is ready for use, resolve promise to add the script's directive element
        scope.$apply(deferred.resolve());
      };
      document.body.appendChild(script);
      return deferred.promise;
    }
    else { //this script has been loaded before
      return scriptPromises[loadFile]; //return the resolved promise from cache
    }
  }

  return directiveReturn;
});

app.directive('myFooDirective', function() {
  return {
    restrict: 'A',
    link: function(scope, element) {
      //put the logic from your lazy loaded "foo.js" script here
      element.text(foo.someFunction());
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

示例延迟加载脚本:

var foo = {
  someFunction: function() {
    return 'I am data from a lazy loaded js function!';
  }
};
Run Code Online (Sandbox Code Playgroud)

有很多方法可以实现我在这里展示的概念.只要想想你将如何使用它,并编写一些指令来实现它.Angular使大多数事情变得非常简单.

注意:注入脚本标记是可选的 - 但我更喜欢它,而不是直接执行脚本.使用脚本标记时,您将能够使用"脚本"部分中"资源"下的开发工具跟踪所有已加载的文件.


小智 9

实际上我不太了解angular的指令和它的模块化的东西,但是我的基本知识我构建了一些预加载函数来加载我的JS文件.... loadScript函数在我的app.js中定义,它包含在主html页面中.

function loadScript(src,callback){

    var script = document.createElement("script");
    script.type = "text/javascript";
    if(callback)script.onload=callback;
    document.getElementsByTagName("head")[0].appendChild(script);
    script.src = src;
}
Run Code Online (Sandbox Code Playgroud)

内部控制器使用这样的东西

app.controller('myCtrl', function($scope) {
  //array of things to load are saved in a JavascriptFile
  loadScript("URL_To_JavascriptFile");
});
Run Code Online (Sandbox Code Playgroud)