Hit*_*dha 10 angularjs angularjs-filter
我想将所有用户的年龄显示为网格.我正在从facebook上阅读数据.我没有把它存放在任何地方.
我显示的日期如下:
{{ friend.birthday }}
Run Code Online (Sandbox Code Playgroud)
如何显示年龄而不是显示生日.
如果可以创建过滤器而不是如何创建过滤器以及如何应用它.
pix*_*its 34
你可以实现一个功能:
控制器:
$scope.calculateAge = function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
Run Code Online (Sandbox Code Playgroud)
HTML
{{ calculateAge(friend.birthday) }}
Run Code Online (Sandbox Code Playgroud)
或过滤器:
app.filter('ageFilter', function() {
function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
return function(birthdate) {
return calculateAge(birthdate);
};
});
Run Code Online (Sandbox Code Playgroud)
HTML
{{ friend.birthday | ageFilter }}
Run Code Online (Sandbox Code Playgroud)
年龄算法取自这个SO答案.
[编辑]如果年龄小于1年,并且您想显示月份,则可以修改ageFilter以计算月差:
app.filter('ageFilter', function() {
function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
function monthDiff(d1, d2) {
if (d1 < d2){
var months = d2.getMonth() - d1.getMonth();
return months <= 0 ? 0 : months;
}
return 0;
}
return function(birthdate) {
var age = calculateAge(birthdate);
if (age == 0)
return monthDiff(birthdate, new Date()) + ' months';
return age;
};
});
Run Code Online (Sandbox Code Playgroud)
Demo Plunker - 年龄函数
演示Plunker - 年龄过滤器
演示Plunker - 年龄<1年的年龄过滤器
| 归档时间: |
|
| 查看次数: |
23500 次 |
| 最近记录: |