这是我计算年龄的代码。我在ng-change
中对多个输入使用相同的方法。
但是我可以使用单一方法仅对一个输入字段绑定年龄。
为什么要和#39; t我使用单一方法根据模型名称绑定多个输入的结果数据?
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>
&#13;
我知道我可以通过传递输入ID来做。但我正在尝试它的型号名称。
答案 0 :(得分:1)
试试这个:$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
}
})
答案 1 :(得分:1)
您必须在方法中传递data
的引用并修改它。
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;
}
})
&#13;
<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>
&#13;