Reputation: 3074
I'm trying to format addresses that have components missing, like
{{name}}<br/>
{{street}}<br/>
{{cityStateZip}}<br/>
Edit - my "street" expression might actually look like this:
{{address.number}} {{address.street}} {{address.apartment}}<br ng-show="address.number && address.number.trim().length>0 && address.street && address.street.trim().length > 0"
and so on.
Some of the address components are optional, like some addresses won't have a street. For those, I don't want a line break. I think I can do this:
{{street}}<br ng-show="street.length == 0"/>
but, the expression for street might be more complex (like number and street) and it might be undefined or it might be an empty string. As a result, all those ng-show expressions will become long and redundant.
So what I'd really like is a show expression that refers to the tag's contents, like:
<span ng-show="thisTagsContents.length>0">{{some expression}}<br/><span>
...where, if it existed, "thisTagsContents" is equivalent to the rendered output of "some expression". Do I have to make my own directive for this, or is there something already in angular to help? Or maybe I'm thinking about it the wrong way altogether?
Thanks.
Upvotes: 1
Views: 472
Reputation: 3074
Thanks for the helpful answers. In case this helps somebody else, I did the following:
// this will show text with a <br> conditionally if the text is non-blank
angular.module('myApp.directives').directive('brIf', function () {
return {
scope: {
text: '='
},
template: '<span ng-show="text && text.trim().length">{{ text }}<br/></span>'
};
});
So I can use it like this:
<br-if text="address.number + ' ' + address.street + ' ' + address.apt"></br-if>
I need to learn more about directives because I want to use it like this:
<br-if>{{address.number}} {{address.street}} {{address.apt}}</br-if>
to avoid all of the string math and the text= attribute, but I don't know how to get the contents of the element back into the template.
Upvotes: 0
Reputation: 1345
You can hide your check behind a method if you dont want to pollute your html code
For example: In your controller write this:
$scope.hideAddress = function(address) {
if (address.number === undefined) {
return true;
}
// arbitrary other checks
return false;
}
Then you can use it in your html
<br ng-show="hideAddress(address)"/>
Upvotes: 1
Reputation: 28610
<span ng-show="some_expression.length>0">{{some_expression}}<br/><span>
You can use .length for your expression , I mean for example :
<span>{{some_expression.length}}<br/><span>
// This will show the character length of your expression
every output in the {{}} have a length property because this is Javascript and in javascript , objects have a length property in their prototype So u can use your ng-show based on the length of that object
Upvotes: 1