[英]AngularJS ng-include only once
如何使用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
时,所有这些东西都会重新加载。
您有很多解决方案,但目前只有两个
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>
干杯
如何仅使用一个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个)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.