2

我注意到对我来说似乎是一个错误,但可能更多的是我滥用$compileAngularJS 中的服务:我有一个名为“动态”的指令,它编译 angularjs 代码并将其显示到一个 div 中。我在这种情况下编译的代码包含ng-controllers并且那些控制器正在监听事件。问题是显然控制器在被替换后并没有“死”,因为应该消失的控制器仍然会对事件(如$routeChangeSuccess或任何其他事件)做出反应。这是一个显示问题的工作plunkr 。让我们看看我的问题的示例代码:

我正在使用的指令

app.directive('dynamic', function ($compile) {
    return {
        restrict: 'A',
        replace: true,
        link: function (scope, element, attrs) {
            scope.$watch(attrs.dynamic, function(html) {
                element.html(html);
                $compile(element.contents())(scope);
            });
        }
    };
});

主控制器,其次是我包括的控制器:

app.controller('TestCtrl', function($scope) {
  $scope.dynamicContent = "Default content";

  $scope.firstButton = function() {
    $scope.dynamicContent = "<div ng-controller='FirstCtrl'>The div from first button</div>";
  }

  $scope.secondButton = function() {
    $scope.dynamicContent = "<div ng-controller='SecondCtrl'>The div from second button</div>";
  }

  $scope.checkButton = function() {
    $scope.$broadcast('checkEvent');
  }
});

app.controller('FirstCtrl', function($scope) {
  $scope.$on('checkEvent', function() {
    alert(1);
  });

});
app.controller('SecondCtrl', function($scope) {
  $scope.$on('checkEvent', function() {
    alert(2);
  });
});

现在,如果我打电话firstButton()then secondButton()then checkButton(),而不是只alert(2)收到 ,我会收到两个警报。如果我点击按钮 1/2/1/2/1/2/1/2,它将向我显示与我点击的按钮一样多的警报。

我在这里做错了什么?

谢谢,希尔纽斯

4

1 回答 1

2

你真的很亲近。首先,我会告诉你你可能想做的事情,因为我不知道你对 $compile 服务的意图。然后我将解释为什么你不需要 $compile 服务来处理这个特定的实例,因为你有效地复制了 ng-include。

你可能想要做什么:

使用指令的关键(尤其是在尝试“$compile”动态内容时,确保您知道在哪里传递了哪个范围。对于 angularjs 中内置的大多数指令,angular 会自动处理创建(通过scope.$new())和销毁(通过scope.$destroy())。由于您没有明确地 '$destroy'-ing 范围,它们不会被删除。另一个问题是您直接将“动态”指令附加到当前范围而不创建子范围或指令中的隔离范围(通过 $new):

Plunkr 示例

app.directive('dynamic', function ($compile) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
          var curScope = null,
              curEle = null;

          function removeOld(){
            if( curScope ){
              curScope.$destroy();
              curScope = null;
              curEle.remove();
              curEle = null;
            }
          }

            scope.$watch(attrs.dynamic, function(html) {
                removeOld();
                curScope = scope.$new(); //creates child scope (not isolate)
                //probably should do some proper escaping here see $sce service
                curEle = angular.element( html );
                if( !curEle.length ){
                  curEle = angular.element('<span>'+html+'</span>');
                }
                $compile( curEle )(curScope);
                element.append( curEle );
            });
        }
    };
});

你可能应该做的:

对于像这样的一些小模板,您可能应该考虑将它们放入 $templateCache(通过 put 如下面的 plunkr 所示),以便对模板的任何请求都可以自动加载它。您还必须考虑其他一些事情,例如“html 是否已正确清理?” 或“我是否希望我的内容正确动画化?”。这些事情会在 ng-include 中自动处理,这几乎就像您试图复制的那样。

Plunkr 示例

app.run(function( $templateCache ){
  $templateCache.put("btn_default.html", "Default content");
  $templateCache.put("btn_one.html", "<div ng-controller='FirstCtrl'>The div from first button</div>");
  $templateCache.put("btn_two.html", "<div ng-controller='SecondCtrl'>The div from second button</div>");
})

现在您所要做的就是使用预先构建的ng-include 指令,如下所示:

<div ng-controller="TestCtrl">
      <div class="btn btn-default" ng-click="firstButton()">First button</div>
      <div class="btn btn-default" ng-click="secondButton()">Second button</div>
      <div class="btn btn-default" ng-click="checkButton()">Check events</div>
      <div ng-include="dynamicContent"></div>
</div>

ng-include 源来帮助你

希望这有助于更好地理解。

于 2014-03-16T06:43:21.307 回答