【问题标题】:AngularJS - How to refresh directive scopeAngularJS - 如何刷新指令范围
【发布时间】:2016-12-27 16:10:08
【问题描述】:

我创建了一个简单的 datepicker 指令,它有一个“选项”。

所以我用一组选项启动日期选择器,然后由于业务逻辑我更改了这些选项,但这并没有被刷新。

在本例中,我需要将“endDate”的日期选择器开始日期更新为与“startDate”相同的日期。

这是我的代码:

指令:

function datepicker() {
    return {
        restrict: "A",
        scope: {
            options : '='
        },
        link: function(scope, element, attrs) {

            var opts = scope.options || {};

            element.datepicker({
                keyboardNavigation: false,
                forceParse: false,
                autoclose: true,
                useCurrent: true,
                format: opts.format || 'dd/mm/yyyy',
                startDate : opts.startDate || ''
            });
        }
    };
}

控制器:

$scope.evaluation = {};

$scope.startDatepickerOptions = {
    startDate : new Date()
};

$scope.endDatepickerOptions = {
    startDate : new Date()
};

$scope.$watch('evaluation.startDate', function(newValue) {
    $scope.endDatepickerOptions.startDate = newValue;
});

查看:

<input type="text" ng-model="evaluation.startDate" name="startDate" datepicker options="startDatepickerOptions"/>

<input type="text" ng-model="evaluation.endDate" name="endDate" datepicker options="endDatepickerOptions"/>

【问题讨论】:

标签: javascript angularjs angularjs-directive datepicker


【解决方案1】:

所以这是解决方案:

我需要在指令链接函数上添加一个相等观察器。到目前为止,由于日期/字符串问题,我已经实现了moment.js library

这是最终代码:

指令(链接功能)

link: function(scope, element, attrs) {

    var opts = scope.options || {};

    element.datepicker({
        keyboardNavigation: false,
        forceParse: false,
        autoclose: true,
        useCurrent: true,
        format: opts.format || 'dd/mm/yyyy',
        startDate : opts.startDate || ''
    });

    scope.$watch('options.startDate', function(newValue) {
        if(newValue) {
            element.datepicker('setStartDate', newValue);
            element.datepicker('setDate', "");
        }
    });
}

控制器

$scope.startDatepickerOptions = {
    startDate : moment().toDate()
};

$scope.endDatepickerOptions = {
    startDate : moment().toDate()
};

$scope.$watch('evaluation.startDate', function(newValue) {
    if(newValue)
        $scope.endDatepickerOptions['startDate'] = moment(newValue, "DD-MM-YYYY").toDate();
});

【讨论】:

    猜你喜欢
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    • 2016-02-06
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    • 1970-01-01
    相关资源
    最近更新 更多