Reputation: 133
How to display '--' incase of ng-repeat value is null in angularjs?
Note: I need to display '--' only when value is null, not when value is zero.
Tried using {{x.daysSinceMaintenanceUpdate || '--'}}, but it displays '--' even when value is zero.
Upvotes: 4
Views: 4547
Reputation: 33726
As a best practice, NEVER put validations directly within your HTML template. That leads to increased effort in code maintenance in the future.
Always avoid a piece of code that will be used repeatedly in your code.
That kind of validation (empty checkings) for sure will be used in your entire application, so, create utility methods, components, services, Etc., for doing that and then inject it into your controller when are needed.
For example:
Create a service with a utility method defaultIsEmpty
.
var myModule = angular.module('myModule', []);
myModule.service('utilities', function() {
this.defaultIsEmpty: function(value, defaultValue) {
return value == null ? defaultValue : value;
}
});
In your controller inject that service as follow:
app.controller('myCtrl', function($scope, utilities) {
$scope.checkDaysSinceMaintenanceUpdate = function(x) {
return utilities.defaultIsEmpty(x.daysSinceMaintenanceUpdate, '--');
}
});
In your HTML template:
{{ checkDaysSinceMaintenanceUpdate(x) }}
Conclusion: Creating services you're avoiding repeated code and for a nice future you will be able to execute maintenance without a headache.
Hope this helps!
Upvotes: 1
Reputation: 13356
Zero is falsy. Use ternary operator:
{{ x.daysSinceMaintenanceUpdate == null ? '--' : x.daysSinceMaintenanceUpdate }}
Upvotes: 9
Reputation: 4629
You could try
{{x.daysSinceMaintenanceUpdate >= 0 ? x.daysSinceMaintenanceUpdate : '--'}}
but it's not very pretty. I think it's better to evaluate why the number value is null sometimes and go from there.
Upvotes: 0