How to check if a scope variable is undefined?
This does not work:
<p ng-show="foo == undefined">Show this if $scope.foo == undefined</p>
How to check if a scope variable is undefined?
This does not work:
<p ng-show="foo == undefined">Show this if $scope.foo == undefined</p>
Using undefined
to make a decision is usually a sign of bad design in Javascript. You might consider doing something else.
However, to answer your question: I think the best way of doing so would be adding a helper function.
$scope.isUndefined = function (thing) {
return (typeof thing === "undefined");
}
and in the template
<div ng-show="isUndefined(foo)"></div>
try this angular.isUndefined(value);
https://docs.angularjs.org/api/ng/function/angular.isUndefined
You can use the double pipe operation to check if the value is undefined the after statement:
<div ng-show="foo || false">
Show this if foo is defined!
</div>
<div ng-show="boo || true">
Show this if boo is undefined!
</div>
For technical explanation for the double pipe, I prefer to take a look on this link: https://stackoverflow.com/a/34707750/6225126
Posting new answer since Angular behavior has changed. Checking equality with undefined now works in angular expressions, at least as of 1.5, as the following code works:
ng-if="foo !== undefined"
When this ng-if evaluates to true, deleting the percentages property off the appropriate scope and calling $digest removes the element from the document, as you would expect.
If you're using Angular 1, I would recommend using Angular's built-in method:
angular.isDefined(value);
reference : https://docs.angularjs.org/api/ng/function/angular.isDefined
Here is the cleanest way to do this:
No need to create a helper function in the controller!