AngularJS - Add computation value from a function to the scope

孤街醉人 提交于 2019-12-22 17:47:32

问题


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);
    }
};

The result of the calculation is shown here.

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

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.


回答1:


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

HTML

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

Controller

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

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

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



来源:https://stackoverflow.com/questions/17397996/angularjs-add-computation-value-from-a-function-to-the-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!