AngularJS - Add computation value from a function

2019-05-28 17:33发布

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条回答
做自己的国王
2楼-- · 2019-05-28 18:08

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

查看更多
登录 后发表回答