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.
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.
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!