Javascript 相同条件下的多个ng-性能方面
我有一个包含不同元素的html页面,根据某些条件(相同条件),它将使用Angular的ng if显示/隐藏 在我的控制器中,我创建了一个Javascript 相同条件下的多个ng-性能方面,javascript,angularjs,angularjs-ng-show,angularjs-ng-if,Javascript,Angularjs,Angularjs Ng Show,Angularjs Ng If,我有一个包含不同元素的html页面,根据某些条件(相同条件),它将使用Angular的ng if显示/隐藏 在我的控制器中,我创建了一个boolean变量 $scope.myCondition = getValue(); 在我看来,我使用ng if指令来听这个变量 性能更好的是什么 在这种情况下,使用多个ng写入清洁代码,但如果: --a-- --A-- --文本,文本,文本-- --b-- --B-- --文本,文本,文本-- --c-- --C-- --文本,文本,文本-- 你说得对,
boolean
变量
$scope.myCondition = getValue();
在我看来,我使用ng if
指令来听这个变量
性能更好的是什么
ng写入清洁代码,但如果:
--a--
--A--
--文本,文本,文本--
--b--
--B--
--文本,文本,文本--
--c--
--C--
--文本,文本,文本--
你说得对,你将为每一个使用过的ng if创建一个观察者,因此在性能方面,最好使用第二个选项
但是,如果您的条件只被评估一次(当控制器执行其代码时),您可以对ng if使用一次性绑定操作符::以避免$watchers。您是对的,您将为每个使用的ng if创建一个watcher,因此在性能方面,最好使用第二个选项
但是,如果您的条件只需要评估一次(当控制器执行其代码时)您可以将一次性绑定操作符::与ng if一起使用,以避免$watchers。这里有一种方法可以获得与第一种方法类似的预期结果,即使用
ng开关。
。下面是它的工作原理
下面是使用ng开关的HTML
<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 switch
。下面是有关其工作原理的详细信息
下面是使用ng开关的HTML
<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开关,您不必担心多种情况,维护更干净的代码与ng if不同。每个开关都有自己的手表,因此从性能角度看,第二个更好。每个开关都有自己的手表,因此从性能角度看,第二个更好。