I have the following list of objects:
[
{ "name" : "foo", "description" : "description of foo..." },
{ "name" : "bar", "description" : "description of bar..." },
{ "name" : "baz" },
...
]
All objects have a name
, but some have an associated description
, and the rest do not.
I use the following template with an input
field connected to a typeahead, to show each matching object:
<script type="text/ng-template" id="my-template.html">
<a style="text-align: left;">
<span style="font-size: 18px; display:block;">{{match.model.name}}</span>
<span ng-show="typeof({{match.model.description}}) !== 'undefined'">{{match.model.description}}</span>
</a>
</script>
I would like the template to show the description
only when its value is defined, but my use of ng-show
returns parsing errors.
How should I use ng-show
or another directive to render the description
, only when this object key (and its value) is available?
I have the following list of objects:
[
{ "name" : "foo", "description" : "description of foo..." },
{ "name" : "bar", "description" : "description of bar..." },
{ "name" : "baz" },
...
]
All objects have a name
, but some have an associated description
, and the rest do not.
I use the following template with an input
field connected to a typeahead, to show each matching object:
<script type="text/ng-template" id="my-template.html">
<a style="text-align: left;">
<span style="font-size: 18px; display:block;">{{match.model.name}}</span>
<span ng-show="typeof({{match.model.description}}) !== 'undefined'">{{match.model.description}}</span>
</a>
</script>
I would like the template to show the description
only when its value is defined, but my use of ng-show
returns parsing errors.
How should I use ng-show
or another directive to render the description
, only when this object key (and its value) is available?
4 Answers
Reset to default 3You should only check for variable value, that's enough
<span ng-if="match.model.description">{{match.model.description}}</span>
<script type="text/ng-template" id="my-template.html">
<a style="text-align: left;">
<span style="font-size: 18px; display:block;">{{match.model.name}}</span>
<span ng-show="match.model.description">{{match.model.description}}</span>
</a>
</script>
Just use it without typeof
- and don't use the curly brackets, as ng-show
is already relative to your scope. In JavaScript, if(undefined)
has the same oute as if(false)
(see Undefined variables, value == false versus !value)
<script type="text/ng-template" id="my-template.html">
<a style="text-align: left;">
<span style="font-size: 18px; display:block;">{{match.model.name}}</span>
<span ng-show="match.model.description">{{match.model.description}} </span>
</a>
</script>
use ng-if="match.model.description"
instead of ng-show
. ngIf differs from ngShow in that ngIf pletely removes and recreates the element in the DOM rather than changing its visibility via the display css property.