1

I've created a simple datepicker directive which have an "options".

So I start the datepicker with a set of options, and then because of business logic I change those options, but this are not being refreshed.

In this example, I need to update de datepicker start date of the "endDate" to the same date as "startDate".

Here's my code:

Directive:

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

Controller:

$scope.evaluation = {};

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

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

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

View:

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

<input type="text" ng-model="evaluation.endDate" name="endDate" datepicker options="endDatepickerOptions"/>
2
  • Have you had a look at this SO Question? Commented Dec 27, 2016 at 16:20
  • Does not work for me Commented Dec 27, 2016 at 16:53

1 Answer 1

1

So here's the solution:

I needed to add an equality watcher on the directive link function. So far, due to dates/strings issues, I've implemented the moment.js library

Here's the final code:

Directive (link function):

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', "");
        }
    });
}

Controller:

$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();
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.