如何展示' - '在angularjs?
中,ng-repeat值的值为null注意:我需要显示' - '仅当值为null时,不是当值为零时。
尝试使用{{x.daysSinceMaintenanceUpdate || ' - '}},但它会显示' - '即使价值为零。
答案 0 :(得分:3)
零是假的。使用三元运算符:
{{ x.daysSinceMaintenanceUpdate == null ? '--' : x.daysSinceMaintenanceUpdate }}
答案 1 :(得分:1)
作为最佳做法,绝不要将验证直接放在HTML模板中。这将导致未来代码维护工作的增加。
始终避免在代码中重复使用的一段代码。
这种验证(空检查)肯定会在整个应用程序中使用,因此,创建实用程序方法,组件,服务等等,然后在需要时将其注入控制器。
例如:
使用实用程序方法defaultIsEmpty
创建服务。
var myModule = angular.module('myModule', []);
myModule.service('utilities', function() {
this.defaultIsEmpty: function(value, defaultValue) {
return value == null ? defaultValue : value;
}
});
在您的控制器中注入该服务,如下所示:
app.controller('myCtrl', function($scope, utilities) {
$scope.checkDaysSinceMaintenanceUpdate = function(x) {
return utilities.defaultIsEmpty(x.daysSinceMaintenanceUpdate, '--');
}
});
在您的HTML模板中:
{{ checkDaysSinceMaintenanceUpdate(x) }}
结论:创建服务,避免重复代码,为了一个美好的未来,您将能够毫不费力地执行维护。
希望这有帮助!
答案 2 :(得分:0)
你可以尝试
{{x.daysSinceMaintenanceUpdate >= 0 ? x.daysSinceMaintenanceUpdate : '--'}}
但它不是很漂亮。我认为最好有时候评估数值为零的原因并从那里开始。