AngularJS - 将计算值从函数添加到作用域 [英] AngularJS - Add computation value from a function to the scope

查看:22
本文介绍了AngularJS - 将计算值从函数添加到作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个使用 AngularStrap datepicker 指令实现的 datepicker 字段:http://mgcrea.github.io/angular-strap/.

I have two datepicker fields which is implemented using AngularStrap datepicker directives: http://mgcrea.github.io/angular-strap/.

<input type="text" name="startDate" ng-model="startDate" data-date-format="dd/mm/yyyy" placeholder="DD/MM/YYYY" bs-datepicker />
<button type="button" class="btn" data-toggle="datepicker">
    <i class="icon-calendar"></i>
</button>

<input type="text" name="endDate" ng-model="endDate" data-date-format="dd/mm/yyyy" placeholder="DD/MM/YYYY" bs-datepicker />
<button type="button" class="btn" data-toggle="datepicker">
    <i class="icon-calendar"></i>
</button>

我还有一个控制器来计算两个日期字段的差异.开始日期和结束日期.

I also have a controller which calculates the difference of the two date fields. The startDate and endDate.

$scope.numberOfDays = function() {
    if ($scope.startDate != null && $scope.endDate != null) {
         var startDate = $scope.startDate;
         var endDate = $scope.endDate;

         var millisecondsPerDay = 1000 * 60 * 60 * 24;
         var millisBetween = endDate.getTime() - startDate.getTime();
         var days = millisBetween / millisecondsPerDay;

         return Math.floor(days);
    }
};

计算结果如下所示.

<input type="text" name="numberOfDays" ng-model="numberOfDays" 
value="{{numberOfDays()}} disabled />

现在,通过 datepicker 选择日期后,当我查看范围时,startDate 和 endDate 都只显示带有空白数组的值:{ }你知道这里有什么问题吗?另外,您如何将 numberOfDays() 添加到当前范围.我尝试添加 ng-model="numberOfDays" 但在处理计算时,numberOfDays 中的范围值仍然为空.任何帮助和建议将不胜感激.

Now, after selecting the dates through datepicker, when I look into my scope, both startDate and endDate are only showing values with blank arrays: { } Do you know what is the issue here? Also, how do you add numberOfDays() to the current scope. I tried adding ng-model="numberOfDays" but when the calculation is being processed the scope value in numberOfDays is still null. Any help and suggestion will be appreciated.

推荐答案

设置观察 监听器以了解天差异表达式的变化,例如

Set up a watch listener for changes to the days difference expression, eg

HTML

<input type="text" name="numberOfDays" ng-model="numberOfDays" />

控制器

$scope.$watch(function() {
    return Math.floor(($scope.endDate - $scope.startDate) / 86400000);
}, function(days) {
    $scope.numberOfDays = days;
});

从这里获取的简化天数计算 - https://stackoverflow.com/a/544429/283366

Simplified days calculation taken from here - https://stackoverflow.com/a/544429/283366

Plunker 示例 - http://plnkr.co/edit/MPNh7O?p=preview

Plunker example here - http://plnkr.co/edit/MPNh7O?p=preview

这篇关于AngularJS - 将计算值从函数添加到作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆