Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'f' character is considered as true in a ng-show

Tags:

angularjs

When using angular, I had a very strange issue:

<div ng-app>
    <textarea ng-model="resp" placeholder="Response"></textarea>
    <a ng-show="resp">Respond</a>
</div>

Fiddle

When writing something into the textarea, the Respond link is shown.

However, strangely, when writing the letter 'f', the Respond button doesn't show.

A workaround for this is to use the condition resp.length>0, but I wonder why the letter 'f' behaves in a special way.

like image 590
edi9999 Avatar asked Jan 11 '23 01:01

edi9999


1 Answers

Actually 'f' is considered as false.

AngularJS uses the toBoolean function internally to evaluate ng-show / ng-hide expressions.

You should get the same behaviour for "f", "false", "0", "n", "no" and "[]".

You can read more about it here: https://github.com/angular/angular.js/issues/1229.

This is angular's toBoolean function:

function toBoolean(value) {
  if (typeof value === 'function') {
    value = true;
  } else if (value && value.length !== 0) {
    var v = lowercase("" + value);
    value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
  } else {
    value = false;
  }
  return value;
}

Update:

In AngularJS 1.3+ this behaviour has been removed.

Quote: Due to bdfc9c02, values 'f', '0', 'false', 'no', 'n', '[]' are no longer treated as falsy. The only JavaScript values that are treated as falsy by the expression parser are now: false, null, undefined, NaN, 0 and "".

like image 72
Alexandrin Rus Avatar answered Jan 20 '23 04:01

Alexandrin Rus