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

illeb picture illeb · Sep 2, 2016 · Viewed 15.4k times · Source

I can't get the & operator to work in an Angular ng-if expression (to use with some bit flags). Suppose we have some HTML like this:

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

If value equals 3, then the bitwise operation should return 2 and thus a true value.

However, Angular throws a Syntax Error exception every time. Is the operation not allowed? Or am I doing something wrong?

Link to the plunker.

Edit: I already resolved my issue by using a simple function that does the job:

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

But I really don't like this solution. Is there a way to use it in an ng-if (without using the function, obviously)?

Answer

Michael Liu picture Michael Liu · Sep 2, 2016

You cannot use the bitwise & operator in an Angular expression. According to the 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.

A note on nomenclature: & is the bitwise AND operator; && is the logical AND operator.

UPDATE: Your checkFlag function is probably the best workaround because its name makes it clear what it does (and that's what I would use), but if you absolutely don't want an extra function, you can use the following equivalent expression:

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

In general, (value & x) != 0 (where x is a power of 2) is equivalent to value % (2 * x) >= x.