82

I'm wanting to show/hide a div based on whether a variable is null or not.

<div ng-show="myvar"></div>

Note: the variable in my case is an object.

A very simple question, but I can't seem to make it work.

Thanks.

Paul Haggo
  • 1,298
  • 1
  • 11
  • 19
  • Related: http://stackoverflow.com/questions/14164371/inline-conditionals-in-angular-js – Robert Harvey Jan 27 '14 at 21:08
  • myvar == null perhaps – Gruff Bunny Jan 27 '14 at 21:15
  • 2
    What non-null values does `myvar` assume? `ng-show` will show for any [truthy](http://www.sitepoint.com/javascript-truthy-falsy/) value, so as long as `myvar` isn't `false`, `null`, `undefined`, `0`, the empty string or `NaN` it should work. Please post some more code for context. – Philipp Reichart Jan 27 '14 at 21:38
  • To clarify, the above example does work, my code did not for unrelated reasons. If mylar is false, null or has never been used before (i.e. $scope.myvar or $rootScope.myvar never called), the div will not show. Once any value has been assigned to it, the div will show, except if the value is specifically false. – Paul Haggo Dec 16 '14 at 00:06

3 Answers3

202
<div ng-hide="myvar == null"></div>

or

<div ng-show="myvar != null"></div>
Yassin Hajaj
  • 20,020
  • 9
  • 41
  • 81
Gruff Bunny
  • 26,318
  • 10
  • 66
  • 56
  • 16
    It is a good practise to use `
    ` instead of `
    `. It's more readable.
    – maicher Jan 11 '15 at 13:05
  • 12
    @maicher That really depends on the context – Petr Peller Jan 25 '15 at 20:35
  • does ng-show translates the expression as `$scope.myvar != $scope.null` or `$scope.myvar != null`? (posted question here http://stackoverflow.com/questions/31387397 ) – jperelli Jul 13 '15 at 15:27
  • Angular will use the javascript null. You really don't want to start adding null to scope anyway as null should always be null (plus angular will ignore the $scope.null it if used in an expression). – Gruff Bunny Jul 13 '15 at 16:20
20

To clarify, the above example does work, my code in the example did not work for unrelated reasons.

If myvar is false, null or has never been used before (i.e. $scope.myvar or $rootScope.myvar never called), the div will not show. Once any value has been assigned to it, the div will show, except if the value is specifically false.

The following will cause the div to show:

$scope.myvar = "Hello World";

or

$scope.myvar = true;

The following will hide the div:

$scope.myvar = null;

or

$scope.myvar = false;
Paul Haggo
  • 1,298
  • 1
  • 11
  • 19
2

In this case, myvar should be a boolean value. If this variable is true, it will show the div, if it's false.. It will hide.

Check this out.

Rodrigo Oliveira
  • 893
  • 5
  • 15