This is my code to calculate age.I am using same method for multiple inputs in ng-change
.
but I can bind age for only one input field using single method.
Why don't I use single method to bind result data for multiple inputs based on model name?
var app = angular.module('myApp', []) app.controller('myController', function($scope) { $scope.calculateAge = function (fieldName,value) {debugger var birthDay =value; var DOB = new Date(birthDay); var today = new Date(); var age = today.getTime() - DOB.getTime(); age = Math.floor(age / (1000 * 60 * 60 * 24 * 365.25)); fieldName=age; //$scope.data1.age=age; } })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp" ng-controller="myController" ng-init="init()"> <div> <input type="date" ng-model="data1.dob" ng-change="calculateAge(data1.age,data1.dob)"/> <input type="text" ng-model="data1.age"/> </div> <div> <input type="date" ng-model="data2.dob" ng-change="calculateAge(data2.age,data2.dob)"/> <input type="text" ng-model="data2.age"/> </div> </div>
I know I can to do by passing input Id's. but am trying it for model name.
just try this: $scope[fieldName] =age;
var app = angular.module('myApp', [])
app.controller('myController', function($scope) {
$scope.calculateAge = function (fieldName,value) {debugger
var birthDay =value;
var DOB = new Date(birthDay);
var today = new Date();
var age = today.getTime() - DOB.getTime();
age = Math.floor(age / (1000 * 60 * 60 * 24 * 365.25));
//fieldName=age;
$scope[fieldName] =age;// $scope[value] is eq. to $scope.data2.age
}
})
You have to pass references of your data
in the method and modify that.
var app = angular.module('myApp', []) app.controller('myController', function($scope) { $scope.calculateAge = function (data) {debugger var birthDay = data.dob; var DOB = new Date(birthDay); var today = new Date(); var age = today.getTime() - DOB.getTime(); age = Math.floor(age / (1000 * 60 * 60 * 24 * 365.25)); data.age = age; } })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp" ng-controller="myController" ng-init="init()"> <div> <input type="date" ng-model="data1.dob" ng-change="calculateAge(data1)"/> <input type="text" ng-model="data1.age"/> </div> <div> <input type="date" ng-model="data2.dob" ng-change="calculateAge(data2)"/> <input type="text" ng-model="data2.age"/> </div> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.