Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
96
rated 0 times [  100] [ 4]  / answers: 1 / hits: 19227  / 8 Years ago, fri, september 2, 2016, 12:00:00

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)?


More From » angularjs

 Answers
12

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.


[#60833] Wednesday, August 31, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
geovannil

Total Points: 226
Total Questions: 99
Total Answers: 103

Location: Zimbabwe
Member since Thu, Jul 21, 2022
2 Years ago
;