When frameworks try to be smart, AngularJS & Expressions

One of my colleagues just discovered this bug/feature in AngularJS. Using an ngIf on a string "no" will result in false.

HTML:

<div ng-app>
    <div ng-controller="yesNoController">
        <div ng-if="yes">Yes is defined, will display</div>
        <div ng-if="no">No is defined, but will not display on Angular 1.2.1</div>
        <div ng-if="notDefined">Not defined, will not display</div>
     </div>
</div>

JavaScript:

function yesNoController($scope) {
    $scope.yes = "yes";
    $scope.no = "no";
    $scope.notDefined = undefined;
}

Will print:

Yes is defined, will display

Let’s read the documentation on expression, to see where this case is covered.

.

.

.

.

Can you find it?

Neither can I.

Fix?

Use the double bang:

        // ...
        <div ng-if="!!no">No is defined, but we need to add a double bang for it to parse correctly</div>
        // ...

JSFiddle can be found here.

For those who care, it’s not a JS thing:

// execute this line in a console
alert("no" ? "no evaluated as true" : "no evaluated as false"); // will alert "no evaluated as true"

3 thoughts on “When frameworks try to be smart, AngularJS & Expressions”

  1. That’s crazy, do you think it’s a deliberately added ‘feature’? Seems very strange, I tried the same trick as you to see if it was something I’d missed about falsey values but as you say it seems to be an Angular thing….

  2. Hopefully, this was removed in the version 1.3.4 (at least, I only tried 1.2.1 and 1.3.4). The screenshot is the piece of the source code in the version 1.2.1 explaining this behavior. I don’t know if it was a serious thing, it’s weird…

Comments are closed.