📜 ⬆️ ⬇️

AngularJS: non-standard ng-if behavior


The project uses angularjs, the project is already quite large, we use a lot of custom directives, but today I am faced with the problem of ng-if behavior.

For me it was expected that the condition works the same as in js, that is:

 if (condition) { ... } else { .... } 

')
Depending on what is transmitted, the item will be hidden or shown.



In my case, the presence of a field in the ng-if="column.is_available" . The field type is a string, but there can be several options:


Everything was fine until I checked No. It turns out that angularjs uses the toBoolean function, when checking a condition that has a fairly uncommon (at least for me) behavior :

 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; } 


That is, it returns false on lines:


The official documentation says nothing about this. Maybe in some cases it is cool and comfortable, but not mine. At a minimum, for such checks, you need to use an additional directive, ng-extra-if="condition" , and for the usual ng-if , use the usual if, the same as in js.

Solved the problem like this:

 <div ng-if="isAvailable(row.is_available)"> 


 $scope.isAvailable = function(is_available){ return !!is_available; } 


But you can also:

 <div ng-if="!!row.is_available"> 


This also applies to ng-hide and ng-show .

Source: https://habr.com/ru/post/225243/


All Articles