4

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.

2
  • Why not using a function that evaluates the value and returns empty or the not empty value? Commented Jan 5, 2018 at 13:47
  • Can u provide me an example or working sample ? Commented Jan 5, 2018 at 13:49

3 Answers 3

10

Zero is falsy. Use ternary operator:

{{ x.daysSinceMaintenanceUpdate == null ? '--' : x.daysSinceMaintenanceUpdate }}
Sign up to request clarification or add additional context in comments.

Comments

1

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!

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.