我试图了解 AngularJS 是如何工作的。
我有一个指令 count-Date
可以按月和年计算年龄。
我无法直接写入数据模型,因为我有很多字段,但我想多次使用我的代码。
HTML:
<div>Date of birth first child
month: <input type = "text" id = "MonthFirstChild" ng-model='MonthFirstChild' required maxlength="2" only-Digits month required count-Date>
year: <input type = "text" name='YearFirstChild' ng-model='YearFirstChild' maxlength="4" only-Digits year-Of-Birth required count-Date>
<span ng-model = "AgeFirstChild">{{AgeFirstChild}}</span>
</div>
<div>Date of birth second child
month: <input type = "text" id = "MonthSecondChild" ng-model='MonthSecondChild' required maxlength="2" only-Digits month required count-Date>
year: <input type = "text" name='YearSecondChild' ng-model='YearSecondChild' maxlength="4" only-Digits year-Of-Birth required count-Date>
<span ng-model = "AgeSecondChild">{{AgeSecondChild}}</span>
</div>
JS:
app.directive('countDate', function () {
return {
link: function ($scope, element, attrs) {
element.bind('blur', function(event,el) {
var el = angular.element(element),
month = +el.parent().children().eq(0).val(),
year = +el.parent().children().eq(1).val(),
dateOfBirth = new Date(year,month),
now = new Date(),
today = new Date(now.getFullYear(), now.getMonth()),
age = Math.round((now - dateOfBirth)/(32140800000);
});
}
};
});
我需要帮助重写该指令。
最佳答案
如果您只想计算年龄,那么编写指令有点大材小用 - 您可以简单地编写一个计算年龄的作用域方法,例如:
HTML:
<div>Date of birth first child
month: <input type="number" min="1" max="12" ng-model="MonthFirstChild" required maxlength="2" />
year: <input type="number" min="0" max="9999" ng-model="YearFirstChild" required maxlength="4" />
<span>{{getAge(YearFirstChild, MonthFirstChild)}}</span>
</div>
JS( Controller ):
$scope.getAge = function(year,month) {
var dateOfBirth = new Date(year, month),
now = new Date();
return now.getFullYear() - dateOfBirth.getFullYear();
};
关于javascript - 更新模型 AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23262098/