How to make a directive update ng-model on jquery on event?

ghz 1years ago ⋅ 6695 views

Question

I'm making an AngularJS directive for a jQuery date picker plugin which should update a ng-model when the datepicker date has changed.

Here is the code so far:

angular.module('bootstrap-timepicker', []).directive('timepicker', [
  function() {
    var link;
    link = function(scope, element, attr, ngModel) {
      element.datetimepicker();

      element.on('dp.change', function(event) {
        // update ngModel ?
      });
    };

    return {
      restrict: 'A',
      link: link,
      require: 'ngModel'
    };
  }
]);

How can I update ngModel in the 'dp.change' event considering that scope, element, attr, ngModel are not available when the event is called?

Thanks!


Answer

This is sure thing that any plugin which has been added to angular doesn't update the ng-model of angular scope, we need to manually do it on it's jquery change event. In angular jquery plugin should always binded to DOM using directive, because directive does provide good control over a DOM.

As you asked in your question that ngModel, element, and scope object are not available inside dp.change event of datetimepicker, I don't think so this could be ever possible inside directive link function, you must have been did something else or you missed to explain in the question.

And for udpating ng-model of date picker you need add below code on your dp.change event

element.on('dp.change', function(event) {
  //need to run digest cycle for applying bindings
  scope.$apply(function() {
    ngModel.$setViewValue(event.date);
  });
});

In above code we retrieved updated date from event object, then assigned to the $viewValue( Actual string value in the view ) of ng-model, thereafter in order update that to every where else wherever this ng-model variable has been used we need to run digest cycle manually using $apply() on directive link function scope. The reason behind the we ran the digest cycle is, we need to push that value inside ng-model variable $modalValue( The value in the model, that the control is bound to ).

Working Plunkr

Let me know if you required anything more, I'll get you that detail, Thanks.