Evaluating Boolean Expressions in AngularJS

I am testing ng-show and AngularJS expressions, but I found something that I cannot understand. I created the variable displayed and assigned it the string 'false' (not boolean). The expression displayed && true evaluates to true, and the second div is displayed without problems (because the line and the truth must be true). I know that there are some differences between Angular expressions and JavaScript expressions, however I do not know why the first div is not displayed; it seems that displayed compiled into boolean on Angular.

Here is the jsfiddle: http://jsfiddle.net/micmia/1psf70tv/3/

Template:

 <div ng-controller="MyCtrl"> <div ng-show="displayed">test1</div> <div ng-show="displayed && true">test2</div> </div> 

Controller:

 var myApp = angular.module('myApp', []); myApp.controller('MyCtrl', function ($scope, $parse) { $scope.displayed = 'false'; }); 
+5
source share
3 answers

How angular evaluated the string 'false' and 'f' and some others. There was an open error in it .

See fiddle works with a later version.

+3
source

If you use a string variable in ng-show or ng-hide, you can check the variable as shown below:

Template:

 <div ng-controller="MyCtrl"> <div ng-show="displayed != null">test1</div> <div ng-show="displayed == 'false'">test2</div> </div> 

Controller:

 var myApp = angular.module('myApp', []); myApp.controller('MyCtrl', function ($scope, $parse) { $scope.displayed = 'false'; }); 

now both divs will display correctly

If you use a boolean variable in ng-show or ng-hide, you can check the variable as shown below:

Template:

 <div ng-controller="MyCtrl"> <div ng-show="displayed">test1</div> <div ng-show="!displayed">test2</div> </div> 

Controller:

 var myApp = angular.module('myApp', []); myApp.controller('MyCtrl', function ($scope, $parse) { $scope.displayed = false; }); 

for above boolean condition, the first div will not be shown, and the second div will be shown.

+1
source

Here, I directly passed the string as the attribute value to the ng-show directive, and since, according to javaScript typeConversion, it should be evaluated as true, but this does not happen with string values ​​(the result is false), although it works fine for numeric values.

So, this is a mistake when calculating Boolean expressions in angular expressions.

My code is:

  <div ng-controller="myController"> <input type="text" ng-model="name"> <p>{{name}}</p> <p>{{10+10}}</p> <button type="button" ng-click="myFunction(this)">click Me !!</button> <p ng-show="rabbit">The name is {{ name | uppercase }}</p> </div> 
0
source

All Articles