AngularJS - 模型更改时动态加载Javascript片段

时间:2014-03-21 01:18:28

标签: javascript angularjs

我希望在使用ngSanitize更改模型时动态加载和卸载javascript代码段。

这是一个演示,展示了我尝试做的事情: http://jsbin.com/wenoz/5/edit?html,output

逻辑是这样的:

* Store multiple snippets of JS in a database or string variables
* Load the JS into the DOM dynamically when the user changes an Angular model
* Remove any existing snippet in the DOM an instantiate the new snippet

想法?谢谢!

1 个答案:

答案 0 :(得分:1)

在更改时,您无法完全摆脱javascript运行,一旦执行它就会成为环境的一部分。您可以使用iframe创建一个单独的环境,如果您想要的话,该环境无法直接访问您的网页。如果你想要的是连续运行脚本,你可以把它放在一个数组中并在你的脚本上使用ng-repeat,这样每次都会创建一个新的标记(JSBIN):

<h3>A Demo to Dynamically Add/Remove Javascript with AngularJS</h3>
<button ng-click="setScript(one)">One</button>
<button ng-click="setScript(two)">Two</button>
<button ng-click="setScript(three)">Three</button>


<script ng-repeat="script in scripts" ng-bind-html="script"></script>


<script>
  var app = angular.module('app', ['ngSanitize']);
  app.controller('mainController', function($scope){
    $scope.scripts = [];
    $scope.one = "alert('one')";
    $scope.two = "alert('two')";
    $scope.three = "alert('three')";
    $scope.script = '';
    $scope.setScript = function(script) {
      $scope.scripts = [script];
    }
  });
</script>