TheYouth
TheYouth

Reputation: 159

Using the same directive on multiple elements

I am trying to follow the example from this stackoverflow discussion on date formatting, it works very well for a page only has one single date field. However, if I have more than one date fields on the page, it seems like only the first date field/ng-model will get set, even other date fields are selected.

Below is the HTML template code:

    <div class="input-append" my-Datepickerloaded>
        <input type="text" ng-model="user.StartDate" my-Datepickerformater></input>
        <span class="add-on">
            <i data-time-icon="icon-time" data-date-icon="icon-calendar">
            </i>
        </span>
    </div>


    <div class="input-append" my-Datepickerloaded>
        <input type="text" ng-model="user.EndDate" my-Datepickerformater></input>
        <span class="add-on">
            <i data-time-icon="icon-time" data-date-icon="icon-calendar">
            </i>
        </span>
    </div>

And here is the directive code (myDatePickerformater):

return {
            require: '^ngModel',
            restrict: 'A',
            link: function (scope, elm, attrs, ctrl) {
                var moment = $window.moment,
                    dateFormat = 'MM/DD/YYYY';

                attrs.$observe('myDatepickerformater', function (newValue) {
                    ctrl.$modelValue = new Date(ctrl.$setViewValue);
                });

                ctrl.$formatters.unshift(function (modelValue) {
                    scope = scope;
                    if (!dateFormat || !modelValue) return '';
                    var retVal = moment(modelValue).format(dateFormat);
                    return retVal;
                });

                ctrl.$parsers.unshift(function (viewValue) {
                    scope = scope;
                    var date = moment(viewValue, dateFormat);
                    return (date && date.isValid() && date.year() > 1950) ? date.toDate() : "";
                });
            }
        };

I have tried to do a $scope.$watch on the models they bind to, it seems like even if I am changing the user.EndDate input field, it is always user.StartDate gets the change and user.EndDate remain untouched, even if the "input" field is displaying both fields correctly.

How do I make sure both fields will get their bind model updated correctly?

Thank you for helping.

Upvotes: 8

Views: 14428

Answers (1)

Alex Osborn
Alex Osborn

Reputation: 9851

You need to give your directive an isolated scope.

Right now, multiple instances of the directive are sharing the same scope, so updating your model is not working as expected.

Take a look at docs.angularjs.org/guide/directive

require: '^ngModel',
restrict: 'A',
scope: {
    ...
},
link: function (scope, elm, attrs, ctrl) {
    ....

Upvotes: 6

Related Questions