what i am trying to achieve is to show and element only if an element's value within a JSON object is NOT equal to an empty string ''.
say i have the following json object
{
'id' : 23,
'name' : 'Adrian Reese',
'age' : '',
'location' : ''
}
now with in a partial template where i show the user information i do something like:
<h1>{{ user.name | capitalize }}</h1>
<span class="age">Age: {{ user.age }}</span>
<span class="location">Location: {{ user.location }}</span>
For each user i want the <span>'s to only be visible if the value is not equal to ''. How can i achieve that ?
Using ngShow: http://docs.angularjs.org/api/ng.directive:ngShow
<span ng-show="user.age != ''" class="age">Age: {{ user.age }}</span>
<span ng-show="user.location != ''" class="location">Location: {{ user.location }}</span>
You can wrap your markup e.g. by div element with ng-show:
<div ng-show="user.age != ''">
<h1>{{ user.name | capitalize }}</h1>
<span class="age">Age: {{ user.age }}</span>
<span class="location">Location: {{ user.location }}</span>
</div>
You can use a filter to specify the visible properties rules in code:
http://jsfiddle.net/g/sANcQ/2/
<div ng-controller="Ctrl">
<h1>{{ user.name }}</h1>
<span ng-repeat="(key, value) in user | userVisibleProps" class="{{key}}">{{key}}: {{value}}</span>
</div>
Javascript:
function Ctrl($scope) {
$scope.user = {
'id' : 23,
'name' : 'Adrian Reese',
'age' : '',
'location' : ''
};
}
angular.module('app', [])
.controller('Ctrl', Ctrl)
.filter('userVisibleProps', function(){
return function(user) {
var visibleUser = {};
for(var key in user) {
if(key != 'id' && user[key] !== '') {
visibleUser[key] = user[key];
}
}
return visibleUser;
};
});
angular.bootstrap(document.body, ['app']);