AngularJS - 将函数的计算值添加到范围 [英] AngularJS - Add computation value from a function to the scope
问题描述
我有两个使用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>
我还有一个控制器,可以计算两个日期字段的差异。 startDate和endDate。
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屋!