0

I am trying to create a directive:

     return {
            restrict: 'A', // Attribute Directive
            ngModel: '^ngModel',
            scope: {
                'ngModel': '='
            },
            link: function ($scope: ng.IScope, element, attrs, ctrl) {

                var datePickerOptions = {
                    autoclose: true,
                    format: attrs.aceDatepickerFormat,
                    weekStart: attrs.aceDatepickerWeekstart
                };

                // Attach the datepicker events (must have Bootstrap.DatePicker referenced).
                element.datepicker(datePickerOptions).next().on('click', function () {
                    $(this).prev().focus();
                });

                element.click(() => {
                    ctrl.$setViewValue(new Date());
                });
            }
        };

In this example, when the click event occurs on the element, I wish to use ctrl.$setViewValue to the current date (this is a test).

When the link function is called, scope, element and atts are all populated correctly, however the ctrl is null.

The element is with a div with ng-controller set.

<div ng-controller="Controllers.FormElementsController">
    <input class="form-control date-picker" id="id-date-picker-1" type="text"
           ng-model="DatePickerValue"
           ace-datepicker-weekstart="1"
           ace-datepicker-format="dd-mm-yyyy"
           ace-datepicker="" />

</div>

Why is no controller being passed here?

1 Answer 1

2

You have to use require to pull in the controller (ngModelController in your case):

return {
            restrict: 'A', // Attribute Directive
            require: '^ngModel',

You had it set to ngModel as the property name.

From the docs:

The myPane directive has a require option with value ^myTabs. When a directive uses this option, $compile will throw an error unless the specified controller is found. The ^ prefix means that this directive searches for the controller on its parents (without the ^ prefix, the directive would look for the controller on just its own element).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.