在 Angular ng-if 表达式中使用 &(按位与运算符)

Using & (bitwise AND operator) in Angular ng-if expressions

我无法让 & 运算符在 Angular ng-if 表达式中工作(与某些位标志一起使用)。假设我们有这样的 HTML:

<div ng-if="value & 2"> </div>

如果 value 等于 3,则按位运算应 return 2,因此为真值。

然而,Angular 每次都会抛出一个 Syntax Error 异常。不允许操作?还是我做错了什么?

Link 到 plunker.

编辑:我已经使用一个简单的函数解决了我的问题:

$scope.checkFlag = function(value, flag){
   return value & flag;
}

但我真的不喜欢这个解决方案。有没有办法在 ng-if 中使用它(显然不使用函数)?

问题是您使用的是 & 而不是 &&& 是按位运算符,Angular 不允许在表达式中使用按位运算符。

您不能在 Angular 表达式中使用按位 & 运算符。根据 documentation:

Angular expressions are like JavaScript expressions with the following differences:

  • ...
  • You cannot use Bitwise, , or void operators in an Angular expression.

If you want to run more complex JavaScript code, you should make it a controller method and call the method from your view.

关于命名法的说明:& 按位 AND 运算符; && 逻辑 AND 运算符。

更新: 你的 checkFlag 函数可能是最好的解决方法,因为它的名字清楚地表明了它的作用(这就是我会使用的),但是如果你绝对不想要额外的功能,可以用下面的等价表达式:

<div ng-if="value % 4 >= 2"> </div>

一般来说,(value & x) != 0(其中 x 是 2 的幂)等价于 value % (2 * x) >= x

我不确定你想在这里完成什么,但你正在使用按位 AND 运算符。在 angular 文档中它说:

No Bitwise, Comma, And Void Operators: You cannot use Bitwise, , or void operators in an Angular expression.

AngularJS expression

由于没有人提供解决方案,我假设您可以将 html 修改为:

<body ng-controller="MainCtrl">
   <div ng-if="check(value,2)">Hey! </div>
</body>

$scope.check = function(val, providedInt){
   return val & providedInt;
 };

See plunkr!

可以使用按位管道来实现:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'hasFlags'
})
export class HasFlagsPipe implements PipeTransform {

  transform(flagsL: number, flagsR: number): boolean {
    return (flagsL & flagsR) != 0;
  }

}

用法:

<div [hidden]="flagsL | hasFlags : flagsR">

注意:我正在使用 angular 2+,但遇到了这个 post 所以希望这对其他人有帮助。