Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display empty string when ng-repeat value is null in angularjs

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.

like image 816
Amsaveni Natarajan Avatar asked Sep 14 '25 09:09

Amsaveni Natarajan


2 Answers

Zero is falsy. Use ternary operator:

{{ x.daysSinceMaintenanceUpdate == null ? '--' : x.daysSinceMaintenanceUpdate }}
like image 108
Faly Avatar answered Sep 15 '25 23:09

Faly


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!

like image 37
Ele Avatar answered Sep 16 '25 00:09

Ele