【问题标题】:How to add the content of a file to javascript function如何将文件的内容添加到javascript函数
【发布时间】:2014-05-30 14:43:23
【问题描述】:

我想用另一个文件的内容填充 anglarjs 函数的内容。可以是js文件,json,txt,我不介意。

test.js

$scope.startTest = function () {
/**
 * insert content of details-1.js
 */
}

detials-1.js

var fac = 3;
return fac;

这样最终的函数看起来像

$scope.stratTest = function() {
  var fac = 3;
  return fac;
}

我的目标是根据您选择的测试制定不同的测试程序,并从 startTest 函数启动特定的测试程序。

【问题讨论】:

  • 您为什么要这样做?您尝试解决的问题可能有更好的解决方案。
  • 我的目标是根据您选择的测试有不同的测试程序,并从 startTest 函数开始一个特定的程序。
  • 编写函数来做所有你想做的事情,并让你的输入文件只包含一个数字,表明你想运行哪个测试。
  • 通常 javascript 使用 AMD 或 CommonJS 模块将文件分开。您通常导入整个函数,而不是函数的内容。

标签: javascript angularjs file


【解决方案1】:

你可能应该这样做。

details-1.js

$scope.tests.myTest = function() {
  // Insert test here
}

test.js

$scope.startTest = function() {
  // Loop through all tests
  for (var key in $scope.tests) {
    if ($scope.tests.hasOwnProperty(key)) {
      // Execute test
      $scope.tests[key]( /* args here */ );
    }
  }

  // Or you could just execute a specific test
  $scope.tests.myTest( /* args here */ )
}

注意: $scope.tests 应该在某处初始化。

【讨论】:

    【解决方案2】:

    AFAIK,除非脚本内容内联在 <script> 标记之间,否则无法访问 <script> 标记的文本内容。

    您必须使用 AJAX 下载脚本(以及随之而来的所有 CORS 约束)才能访问文本内容,然后使用 new Function() 将该内容转换为新的函数对象,例如喜欢:

    $http({method: 'GET', url: 'myfunc.js'})
        .success(function(data) {
            $scope.startTest = new Function(data);
            // function may be invoked now
        });
    

    您可能需要调整参数以确保下载的内容被视为纯文本。

    另请注意,生成的函数将没有访问其封闭范围内的任何变量,而不是全局变量。

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-06
      • 1970-01-01
      • 2021-12-10
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      • 2016-05-26
      相关资源
      最近更新 更多