Reputation: 1391
I'm testing the ng-show
and AngularJS expressions, but I found something I can't understand. I created a variable displayed
and assigned a string 'false'
(not boolean) to it. The expression displayed && true
is evaluated to true, and the second div is shown without problem (because a string and true should be true). I know there are some differences between Angular expressions and JavaScript expressions, however I don't know why the first div is not shown; it seems that the displayed
is compiled to a boolean by 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';
});
Upvotes: 6
Views: 19474
Reputation: 208
Here I have directly passed the string as a attribute value to ng-show directive and since as per javaScript typeConversion it should evaluate to true but this is not happening here with string values(result into false),although it is working fine for numeric values.
So this is a bug in evaluating boolean expressions in angularJs.
My Code:
<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>
Upvotes: 0
Reputation: 5825
That's how angular evaluated the string 'false'
and 'f'
and some others as well.
There was an open bug about it.
See this fiddle works with a later version.
Upvotes: 3
Reputation: 26
If you are using string variable in ng-show or ng-hide means you can check the variable like expression 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 div will be shown correctly
If you are using boolean variable in ng-show or ng-hide means you can check the variable like 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 first div will not be shown and second div will be showed.
Upvotes: 0