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

The 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!

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

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.

Method 2

Have a look on this demo http://jsfiddle.net/TheRodeo/taujuuq2/3/
this might give you an idea how to proceed


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment