gpt4 book ai didi

javascript - angularjs - ng-if 多重条件

转载 作者:行者123 更新时间:2023-11-29 16:06:18 27 4
gpt4 key购买 nike

所以之前有人问过这个问题,但我的问题并不像 ng-if="country == 'ireland' || country='United Kingdom'" 这么简单

我需要做类似的事情:

ng-if="(country='ireland' || country='united kingdom') || (name='John' || name='Joe')"

我在做什么:
ng-if="
(settings.eur && title.usa != undefined || title.leak != undefined) || (settings.usa && title.eur != undefined || title.leak != undefined) ||
(settings.leak && title.eur != undefined || title.usa != undefined) ||
(settings.leak == false && settings.eur == false && settings.usa == false)”

但它只会触发第一行,或者至少它看起来是这样。

最佳答案

这里有几点需要考虑:

赋值运算符与相等运算符

使用javascript equality operator (即 ==)而不是 assignment operator (即 =):

ng-if="(country=='ireland' || country=='united kingdom') || (name=='John' || name=='Joe')"

运算符优先级和结合性

此外,请考虑 operator precedence - 是否有条件加入logical AND (即 &&)应该在那些通过 logical OR 加入的人之前被评估(即 ||)。使用 grouping operators (即 () - A.K.A. 括号)使用 right-associativity需要时。

例如,这一行:

(settings.eur && title.usa != undefined || title.leak != undefined)

可以更改为右结合性:

(settings.eur && (title.usa != undefined || title.leak != undefined))

或者保持左结合性:

((settings.eur && title.usa != undefined) || title.leak != undefined)

将逻辑移至 Controller

正如评论中提到的那样,大条件中的逻辑可能应该移到某些 Controller 逻辑中。这将使更新和分离业务逻辑与标记变得更简单。

一种方法是声明一个函数,如下例所示。也许比检查变量是否为 undefined 更简单的方法是将它们初始化为默认 bool 值(例如 false),如下例所示。尝试切换复选框:

angular.module('app', [])
.controller('cont', function($scope) {
$scope.country = 'ireland';
$scope.name = 'Joe';
$scope.settings = {
eur: true,
leak: false,
usa: false
};
$scope.shouldShowLargerComplexContainer = function() {
if (($scope.settings.leak == false && $scope.settings.eur == false && $scope.settings.usa == false)) {
return true;
}
return false;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="cont">
country? name?
<div ng-if="(country=='ireland' || country=='united kingdom') || (name=='John' || name=='Joe')">country Ireland and name is joe or john</div>
Complex logic div?
<div ng-if="shouldShowLargerComplexContainer()">larger complex div</div>
<div>
<input type="checkbox" ng-model="settings.eur" />eur</div>
<div>
<input type="checkbox" ng-model="settings.leak" />leak</div>
<div>
<input type="checkbox" ng-model="settings.usa" />usa</div>
</div>

关于javascript - angularjs - ng-if 多重条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41077945/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com