$ scope变量直到第二次单击才更新(AngularJS / jQuery / Bootstrap Date Range Picker)

时间:2016-06-09 19:37:27

标签: javascript jquery angularjs scope daterangepicker

所以我已经在stackoverflow上搜索了很多,似乎问题与我的相似,但不同。对我来说,视图(具有id =&#34的div类;报告范围")立即更新,以显示用户选择所需日期范围时选择的日期,但是$ scope变量(使用以便我可以通过在用户第二次单击reportrange div之前,所选的开始和结束日期值不会更新。

我在AngularJS中使用bootstrap date range picker

以下是我的控制器中的代码:

//start date when page loads
$scope.startDate = moment().subtract(3, 'years').startOf('year').format('YYYY-MM-DD');    
//end date when page loads
$scope.endDate = moment().add(2, 'years').endOf('year').format('YYYY-MM-DD');  

//updates the startDate and endDate
var updateStartEnd = function (start, end) {
    $scope.startDate = start.format('YYYY-MM-DD');
    $scope.endDate = end.format('YYYY-MM-DD');
    //$log.info($scope.startDate);
    //outputs the correct date but date not changed on the page
    //$log.info($scope.endDate);
    //outputs the correct date but date not changed on the page
}

$scope.dateFunc = function () {

    function cb(start, end) {
        updateStartEnd(start, end);
        $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
    }

    $('#reportrange').daterangepicker({

        ranges: {
           'Last 7 Days': [moment().subtract(6, 'days'), moment()],
           'Last 30 Days': [moment().subtract(29, 'days'), moment()],
           'This Month': [moment().startOf('month'), moment().endOf('month')],
           'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
           'This Year': [moment().startOf('year'), moment().endOf('year')]
        }

    }, cb);
};

这是我的html页面上的日期范围选择器下拉列表:

<div ng-click="dateFunc()" id="reportrange" class="pull-right" style="background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc; width: 100%">
<i class="glyphicon glyphicon-calendar fa fa-calendar"></i>&nbsp;
<span>Select a Date Range...</span> <b class="caret"></b>
</div>

我尝试添加$ scope.watch以及将ng-click更改为ng-init,但这些都没有被证明是有用的。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

我通过添加$ scope。$ apply修复了这个问题,如下所示:

//updates the startDate and endDate
var updateStartEnd = function (start, end) {
    $scope.$apply(function () {
        $scope.startDate = start.format('YYYY-MM-DD');
        $scope.endDate = end.format('YYYY-MM-DD');       
    });
};