Angular JS $编译服务导致$ watch内存泄漏

时间:2015-03-22 03:01:46

标签: javascript angularjs memory-leaks

我想由于误操作,以下一段代码会造成内存泄漏,我无法理解为什么,我已经录制了短视频直播来演示问题,你可以在这里找到它:https://www.youtube.com/watch?v=IWCcOI5kN1c&feature=youtu.be

这是失败的代码,它的作用是它只是动态编译存储在名为content的变量中的html,但是只要你通过textarea开始更改content变量,代码就会开始创建$ watch'es一旦你增加绑定量,情况会变得更糟,对于每个绑定Angular创建新范围(这显然是正确的)但它不会删除旧的并且它们被保存在内存中

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.15/angular.js" data-semver="1.3.15"></script>
      <script>
          var app = angular.module('plunker', []);

          app.controller('MainCtrl', function($scope) {
              $scope.name = 'World';
          });

          app.directive('compile', function($compile) {
              return {
                  restrict: 'A',
                  link: function(scope, elem, attrs) {
                      scope.$watch(attrs.compile, function(newVal) {
                          // create a span (an inline element) so we have an actual DOM node to
                          // set the innerHTML of.
                          var newElem = document.createElement('span');

                          newElem.innerHTML = newVal;

                          // clear out the contents of this element
                          elem[0].innerHTML = '';

                          // and replace it with the raw (uncompiled) node
                          elem[0].appendChild(newElem);

                          // now the node is in the DOM so we can compile it
                          // but we want to use a try..catch because the user
                          // might be in the middle of typing a new expression,
                          // but the syntax right now is not valid so the
                          // expression parser will throw an error.
                          try {
                              // compile the node in the DOM with the existing scope
                              $compile(newElem)(scope);
                          } catch(e) { /* don't need to do anything here */
                          }
                      });
                  }
              };
          });
      </script>
  </head>

  <body ng-controller="MainCtrl" ng-init="variable = 3; content = '{{ variable }}'">
    <div>
      The value of $scope.variable === "{{ variable }}"
    </div>
    <div>
      The value of $scope.content === "{{ content }}"
    </div>
    <br>
    <div>
    The value of $scope.content is <b>ng-model</b>'ed via the following textarea:<br>
    </div>

    <textarea rows="3" ng-model="content"></textarea>

    <div style="border: 1px solid black">
      Instead of rendering the value of the $scope.content field which is currently equal to "{{ content }}" I need to render compiled and evaluated value which should be equal to "{{ variable }}"
    </div>

    <hr>

    <p>Look! It works: <span compile="content"></span></p>
  </body>

</html>

1 个答案:

答案 0 :(得分:4)

好的,我道歉,我不知道内存泄漏有多糟糕! (这是我的指令Lu4正在使用)

我相信我现在已经摆脱了泄漏并且清理得更好了。每次我重新编译并首先销毁旧的子范围时,我创建了一个新的子范围。根据{{​​3}},我确保在清除DOM元素之前销毁范围

this excellent tip

app.directive('compile', function($compile) {
  return {
    restrict: 'A',
    link: function(scope, elem, attrs) {
      var prevScope;
      scope.$watch(attrs.compile, function(newVal, oldVal) {
        // create a span (an inline element) so we have an actual DOM node to
        // set the innerHTML of.
        var newElem = document.createElement('span');
        newElem.innerHTML = newVal;
        // clean up first
        if (prevScope) {
          prevScope.$destroy();
          prevScope = null;
        }
        // clear out the contents of this element
        elem.empty();
        // and replace it with the raw (uncompiled) node
        elem[0].appendChild(newElem);
        // now the node is in the DOM so we can compile it
        // but we want to use a try..catch because the user
        // might be in the middle of typing a new expression,
        // but the syntax right now is not valid so the
        // expression parser will throw an error.
        try {
          // compile the node in the DOM with a child of the existing scope
          prevScope = scope.$new();
          $compile(newElem)(prevScope);
        } catch (e) { /* don't need to do anything here */ }
      });
    }
  }
});