使用 ng-if 和 ng-include 重新创建作用域

Use ng-if with ng-include to recreate scope

我在 ng-repeat 中有一个 ng-include:

<div ng-repeat="tab in tabs" ng-show="tab.active">
  <div ng-include="tab.url" class="no-padding no-margin"></div>
</div>

我只想在用户单击选项卡时将内容加载到 DOM,因此我在 ng-include:

周围使用 ng-if
<div ng-repeat="tab in tabs" ng-show="tab.active">
    <div ng-if="tab.loaded">
        <div ng-include="tab.url" class="no-padding no-margin"></div>
    </div>
</div>

这部分工作正常。但是,我有一个选项卡需要动态内容,因此每次用户单击该选项卡时,我都需要重新创建该控制器的范围。

根据我的理解,我也可以使用ng-if到remove/recreateDOM个元素。根据 ng-if documentation:

The ngIf directive removes or recreates a portion of the DOM tree based on an {expression}

...

when an element is removed using ngIf its scope is destroyed and a new scope is created when the element is restored

我添加了将动态选项卡的 loaded 属性 设置为 false 的代码,这应该会从 DOM 中删除它的内容。

然后我将其设置回 true,以便重新创建范围,但我无法再次创建范围。

我的方法是否正确,或者除了 ng-if 之外还有什么可以用于我的目的。

为什么需要"recreate"范围?如果 ngInclude 的属性在范围内发生变化,则其他页面将被包含并重新编译所有 html。请描述您为什么需要这样做,因为原因可能是错误的。

否则,确实 ngIf 评估为 false 将删除该元素。但前提是它没有立即设置为 true,因为 angular 只有在有机会时才刷新 DOM(你的 HTML),即在当前同步块之后代码。

这不会有任何影响:

$scope.theTab.loaded = false;
$scope.theTab.loaded = true;
// Now Angular enter a digest cycle and see that theTab.loaded has not changed.

这将:

$scope.theTab.loaded = false;
// $timeout will wait for a digest cycle before executing the code
// Angular will remove the tab from the DOM
$timeout(function() {
  $scope.theTab.loaded = true;
  // Here a second digest cycle happen, angular will put the tab back into the DOM
});