我已经看到了类似的问题并且跟着它发球了。 Angular Template Default Value if Binding Null / Undefined (With Filter)
我的对象如下:
{
"image": {
"icon_url": "http://static.giantbomb.com/uploads/square_avatar/9/93770/2496414-dying-light-2013523175751_8.jpg",
"medium_url": "http://static.giantbomb.com/uploads/scale_medium/9/93770/2496414-dying-light-2013523175751_8.jpg",
"screen_url": "http://static.giantbomb.com/uploads/screen_medium/9/93770/2496414-dying-light-2013523175751_8.jpg",
"small_url": "http://static.giantbomb.com/uploads/scale_small/9/93770/2496414-dying-light-2013523175751_8.jpg",
"super_url": "http://static.giantbomb.com/uploads/scale_large/9/93770/2496414-dying-light-2013523175751_8.jpg",
"thumb_url": "http://static.giantbomb.com/uploads/scale_avatar/9/93770/2496414-dying-light-2013523175751_8.jpg",
"tiny_url": "http://static.giantbomb.com/uploads/square_mini/9/93770/2496414-dying-light-2013523175751_8.jpg"
},
"name": "Dying Light",
"original_game_rating": null,
"original_release_date": null,
"objectID": "346569380"
}
我将左侧表达式包装在括号中,但它没有显示" TBA"对于年份为null
的商品。
<span>{{ (getDate(hit.original_release_date) | date:'yyyy') || 'TBA' }}</span>
我有一种感觉,因为我引用了一个函数并且已经使用了一组括号。我该如何解决这个问题......?
对此有任何帮助表示赞赏。提前谢谢!
更新
这里是getDate()
功能:
$scope.getDate = function(date) {
return $filter('dateToISO')(date);
};
dateToISO
过滤器:
.filter('dateToISO', function() {
return function(input) {
var dateTime = input.split(" ");
var date = dateTime[0];
var datePartials = date.split("-");
var time = dateTime[1];
var timePartials = time.split(":");
var formattedDate = new Date();
formattedDate.setFullYear(datePartials[0]);
formattedDate.setMonth(datePartials[1]-1);
formattedDate.setDate(datePartials[2]);
formattedDate.setHours(timePartials[0]);
formattedDate.setMinutes(timePartials[1]);
return formattedDate;
};
})
答案 0 :(得分:5)
也实施默认过滤器。
app.filter('default', [function(){
return function(value, def) {
return value || def;
};
}]);
并将其用作:
<span>{{getDate(hit.original_release_date) | date:'yyyy' | default: 'TBA'}}</span>
<强>更新强>
如果收到dateToISO
或undefined
,您的null
过滤器也可能会失败
检查其输入。
.filter('dateToISO', function() {
return function(input) {
if (!input || !input.match(/^\d{2}-\d{2}-\d{4} \d{2}\:\d{2}\:\d{2}$/)) return;
var dateTime = input.split(" ");
var date = dateTime[0];
var datePartials = date.split("-");
var time = dateTime[1];
var timePartials = time.split(":");
var formattedDate = new Date();
formattedDate.setFullYear(datePartials[0]);
formattedDate.setMonth(datePartials[1]-1);
formattedDate.setDate(datePartials[2]);
formattedDate.setHours(timePartials[0]);
formattedDate.setMinutes(timePartials[1]);
return formattedDate;
};
})
添加强>
在角度方面,你总是要这样做:
<span ng-if="hit.original_release_date">{{getDate(hit.original_release_date) | date:'yyyy'}}</span>
<span ng-if="!hit.original_release_date">TBA</span>
答案 1 :(得分:0)
试试这个:
{{hit.original_release_date ? (hit.original_release date | date:'yyyy') : 'TBA'}}