Search code examples
angularjsangular-ng-if

The tilde operator not working in angularjs?


The tilde operator ~ not working in ng-if directive but I can check the condition like this message.indexOf('angular') > 0. I want to know why the tilde operator not working inside the HTML.

In the html:

<div ng-if="~message.indexOf('angular') ? true : false">...</div>

In the angularJS:

$scope.message = 'Hello angular';

Error appears in the console

angular.js:13920 Error: [$parse:lexerr] Lexer Error: Unexpected next character  at columns 0-0 [~] in expression [~message.indexOf('angular') ? true : false].
http://errors.angularjs.org/1.5.8/$parse/lexerr?p0=Unexpected%20nextharacter%20&p1=s%200-0%20%5B~%5D&p2=~message.indexOf('angular')%20%3F%20true%20%3A%false
    at https://code.angularjs.org/1.5.8/angular.js:68:12
    at Lexer.throwError (https://code.angularjs.org/1.5.8/angular.js:14179:11)
    at Lexer.lex (https://code.angularjs.org/1.5.8/angular.js:14101:16)
    at AST.ast (https://code.angularjs.org/1.5.8/angular.js:14303:30)
    at ASTCompiler.compile (https://code.angularjs.org/1.5.8/angular.js:14771:31)
    at Parser.parse (https://code.angularjs.org/1.5.8/angular.js:15700:29)
    at $parse (https://code.angularjs.org/1.5.8/angular.js:15865:39)
    at ChildScope.$watch (https://code.angularjs.org/1.5.8/angular.js:17104:19)
    at Object.link (https://code.angularjs.org/1.5.8/angular.js:26396:16)
    at https://code.angularjs.org/1.5.8/angular.js:1247:18

Solution

  • Angular's template expression syntax is much like JavaScript expression syntax, but it's still not JavaScript.

    The key differences are listed in the documentation and one of them states

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

    Being a bitwise operator, ~ is not supported.