相同条件下的多个ng-if -性能方面
Multiple ng-if on the same condition - performance wise
我有一个带有不同元素的html页面,根据某些条件(相同的条件),它将使用Angular的ng-if来显示/隐藏。
在我的控制器中,我创建了一个boolean
变量。$scope.myCondition = getValue();
在我看来,我听这个变量使用ng-if
指令。
性能如何更好:
- 在此条件下使用多个
ng-if
编写更干净的代码BUT
<div>
<div ng-if="myCondition" >-- a --</div>
<div ng-if="!myCondition">-- A --</div>
<div>
-- text, text, text... --
</div>
<div ng-if="myCondition" >-- b --</div>
<div ng-if="!myCondition">-- B --</div>
<div>
-- text, text, text... --
</div>
<div ng-if="myCondition" >-- c --</div>
<div ng-if="!myCondition">-- C --</div>
<div>
-- text, text, text... --
</div>
</div>
- 写代码副本(在视图中)但是使用单个
ng-if
:
<div ng-if="myCondition">
<div>-- a --</div>
<div>
-- text, text, text... --
</div>
<div>-- b --</div>
<div>
-- text, text, text... --
</div>
<div >-- c --</div>
<div>
-- text, text, text... --
</div>
</div>
<div ng-if="!myCondition">
<div>-- A --</div>
<div>
-- text, text, text... --
</div>
<div>-- B --</div>
<div>
-- text, text, text... --
</div>
<div >-- C --</div>
<div>
-- text, text, text... --
</div>
</div>
我更喜欢编写示例1所示的代码,因为它更易于维护。但我担心这种方式将为每个ng-if
创建一个新的$watch
。
对吗?Angular是否会为每个ng-if
创建新的$watch
,尽管这是相同的静态条件(不是某个函数的返回值,而是一个简单的变量)。
这个问题是关于ng-if
指令的,但也与ng-show
和ng-hide
相关
您是对的,您将为每个使用的ng-if创建一个监视器,因此从性能角度来看,使用第二个选项更好。
但是,如果您的条件只计算一次(当控制器执行其代码时),您可以使用一次性绑定操作符::与ng-if一起使用,以避免$watchers。
这是另一种方法,可以获得与使用ng-switch
的第一种方法相似的预期结果。下面是它如何工作的演示。
下面是你的HTML使用ng-switch
<body ng-app="switchExample">
<div ng-controller="ExampleController">
<input type="text" ng-model ="searchTerm" ng-change="getDisplayText()"/>
<code>selection={{searchTerm}}</code>
<hr/>
<div class="animate-switch-container"
ng-switch on="myCondition">
<div ng-switch-when="Home">Home page</div>
<div ng-switch-when="show test">Test Sample</div>
<div ng-switch-default>default</div>
</div>
</div>
</body>
在你的JS中,你将有
(function(angular) {
'use strict';
angular.module('switchExample', ['ngAnimate'])
.controller('ExampleController', ['$scope', function($scope) {
$scope.getDisplayText = function() {
$scope.myCondition = getValue($scope.searchTerm);
};
$scope.myCondition = getValue('Home');
function getValue(input) {
var cond = input;
if (input === 'Test') {
cond = 'show test';
}
return cond;
};
}]);
})(window.angular);
使用ng-switch,您不必担心多个条件,并且与ng-if不同,维护更干净的代码更容易。
相关文章:
- 我需要NG-IF/NG-SWITCH还是NG-SHOW&NG-HIDE
- 如何应用带过滤器的ng if来过滤记录,并在同一页面中显示两个不同的视图
- 在 ng-if 编译后访问指令中的 DOM 元素
- 通过ng-if设置隐藏文本框的值
- AngularJS ng-if指令在移除元素之前,即使条件为false,也会短暂呈现
- 使用 ng-if 时 ng 类的标记行为
- 为什么更改范围获胜'不能在ng if内部工作,而是通过函数调用AngularJS
- Angular2 ng if有什么问题
- 为什么myForm$提交的不适用于ng消息,但适用于ng if
- ng if不验证函数
- 将默认选项添加到ng-if
- 通过使用ng if更新ng repeat加载程序
- ng-if 连续执行方法
- 如何在使用$http缓存时重新触发ng-if/ng显示动画
- 从指令中向元素添加ng-if属性
- angularjs ng if中的无限循环
- Delete with ng-if?
- ng-if中的日期时间比较
- 使用 ng-if=“的角度性能!!someVar“ vs ng-if=”someVar“.
- 相同条件下的多个ng-if -性能方面