AngularJS ng-仅包括一次

时间:2014-08-28 21:51:39

标签: javascript angularjs angularjs-ng-include

如何使用ng-include以使其内容仅加载一次? 这就是我所拥有的:

<div data-ng-if="%condition-1%" data-ng-include="%url-1%"></div>
<div data-ng-if="%condition-2%" data-ng-include="%url-2%"></div>
<div data-ng-if="%condition-3%" data-ng-include="%url-3%"></div>
...

在我的情况下,某个时刻只有一个条件成立。 在页面生命周期中,任何条件都可以多次更改其值。 因此ng-include会一次又一次地加载相同的内容。 我怎样才能告诉Angular只处理ng-include一次 - 当适当的条件第一次变为真时? 一次加载它们会导致页面被杀死,因为每个模板都很大而且很重。 此外,没有严格的条件更改顺序,例如,condition-3在页面生命周期内可能永远不会成为现实 - 我希望在这种情况下根本不加载url-3内容。 谢谢!

更新 是的,模板已经在缓存中。但它有一个复杂的内部结构,如对外部图像,iframe等的引用 - 所有这些都在我每次使用ng-include时重新加载。

2 个答案:

答案 0 :(得分:1)

你有很多解决方案,但目前我只想到了两个解决方案

1°替换ng-if用于ng-show,因为ng-if删除了dom和所有可用的子范围,迫使框架再次发出请求,而如果你使用ng-show, dom只会被隐藏,请求只能进行一次。

2°如果你确实需要使用ng-if并且服务器中的内容是静态的,你可以通过手动访问angular提供的$ templateCache服务,或者你想要加载的内容,将它缓存在javascript层上是html,您可以在javascript图层上使用$ templateCache服务,也可以使用ng-template标签预加载该数据。

示例:

<script id="url/you/want.html" type="text/ng-template">
<div>I am preloaded dom that responds to the url/you/want.html 
requests made by this application 
</div>
</script>

干杯

答案 1 :(得分:0)

如何仅使用一个ng-include并使用控制器中的某些逻辑来切换使用绑定使用哪个源?这样一次只能加载一个。

控制器

function($scope) {
    $scope.activeTemplate = null; //some default or even null

    $scope.$watch('condition', function(newvalue) {

        //whatever logic you need to switch template

        if (newvalue == 'condition1') {
            $scope.activeTemplate = '/path/to/condition1.html';
        } else if (newvalue == 'condition2') {
            $scope.activeTemplate = '/path/to/condition2.html';
        } else {
            $scope.activeTemplate = '/path/to/default.html';
        }
    });
}

这样一次只能加载一个模板,并且你已经将绑定数量从3减少到1.(但是你可以有效地从3到2添加一个手表)