javascript - 更新模型 AngularJS

标签 javascript angularjs

我试图了解 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/

相关文章:

javascript - 将 NodeJS 回调从导出函数传递到 View

javascript - Angular 未知提供者

javascript - Angular animate runner 未定义

javascript - 如何使用angular-ui bootstrap在angularjs中实现服务器端分页。?

javascript - D3 饼图过渡

javascript - 跟踪目录产品印象 - 增强型电子商务 Google Analytics

javascript - 用于在一张纸上对多个表格进行实时排序的 Google Sheets 脚本

javascript - 关于绑定(bind)值的 Angular 指令

javascript - 如何使用_.map在图表中显示数据

javascript - 谷歌折线图划分网格线