0

In Angular (1.3), I want to be able to enter a dob field of my person object and this has another property called age which calculates the age based on the dob.

So I have the field to enter dob as:

<div class="form-group">
    <input class="form-control" type="date" ng-model="player.dob" placeholder="DD/MM/YYYY" />
</div>

and I display some of the information that the user types, as they type (name, sex, description etc) but when the user enters the dob, I want to automatically display age like this:

<div>{{player.age}}</div>

How can I do that?

Thanks

Rodders
  • 2,425
  • 2
  • 20
  • 34
  • i think here is your answer http://stackoverflow.com/questions/24883308/convert-birthday-to-age-in-angularjs – uzaif Jul 17 '16 at 13:35
  • Nice one, I didn't think about using a filter. I don't even need an age property. Thanks – Rodders Jul 17 '16 at 13:47

2 Answers2

1

I don't know if it's what you're looking for, but if I'm correct you can create a custom filter to display the age based on the dob input, as below:

angular.module('app', [])
  .controller('mainCtrl', function($scope) {
    $scope.player = {};
  })

  .filter('ageFilter', function() {
    return function(dob) {
      var ageDifMs = Date.now() - new Date(dob).getTime();
      var ageDate = new Date(ageDifMs);
      return Math.abs(ageDate.getUTCFullYear() - 1970);
    };
  });
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>

<body ng-controller="mainCtrl">
  <div class="form-group">
    <input class="form-control" type="date" ng-model="player.dob" placeholder="DD/MM/YYYY" />
  </div>
  <hr>
  <div ng-if="player.dob" ng-bind="player.dob | ageFilter"></div>
</body>

</html>
developer033
  • 24,267
  • 8
  • 82
  • 108
0

you can use ngChange

<div class="form-group">
<input class="form-control" type="date" ng-model="player.dob" ng-change="calculateAge()" placeholder="DD/MM/YYYY" />

and then in your controller:

$scope.calculateAge = function(){
    //do the calculations you want
}
nitzanerman
  • 104
  • 1
  • 6