DaCh
DaCh

Reputation: 931

Angular Directive would not update ng-model

I can't seem to find a way to update my ng-model in my directive

My directive looks like this

app.directive('DatepickerChanger', function () {
    return {
        restrict: 'E',
        require: 'ngModel',
        scope: {
            Model: '=',
            startDate: '=',
            endDate: '=',
        },
        templateUrl: function(elem,attrs) {
            return '/AngularJS/Directives/msDatepickerTpl.html'
        },
        link: function (scope, element, attrs, ngModel) {  
               ngModel = new Date();
        }

    }
});

And i use it like this

 <DatepickerChanger ng-model="date" required></DatepickerChanger>

Where date is a other date object

If i console.log the ng-model, i can see that it's change it's value, but can't see it from the place where i call the directive. anyone got a clue to what im doing worng

Upvotes: 1

Views: 1151

Answers (1)

Rafael P. Miranda
Rafael P. Miranda

Reputation: 776

You are using it wrong. This ngModel is a controller. Your code should look like this:

link: function (scope, element, attrs, ngModel) {  
    ngModel.$setViewValue(new Date());
}

Also, the directive should be called datepickerChanger and referenced in html as datepicker-changer

EDIT:

You want to update the ngModel after changing the input, for example. One way to do that is use the bind function to capture the events of the input field (I cant see your template, but I imagine that will have one input):

link: function (scope, element, attrs, ngModel) {  
    element.find('input').bind('change', function() {
       // Do something with this.value 
       ngModel.$setViewValue(newDate);
    });
}

Upvotes: 1

Related Questions