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

2

4

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!

Fraxinella answered 2/3, 2015 at 11:18 Comment(4)
Why not use an Angular datepicker?Grani
Thanks but I want to use a very specific version of a specific date picker for my application.Fraxinella
Any chance you can create a plunker/fiddle replicating this issue?Grani
perhaps this is a silly question, but why do you say these variables are not available at the time the event is called? Can you not just dereference them, since they are part of the outer function?Moretta
F
16

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.

Fowle answered 22/3, 2015 at 11:58 Comment(0)
R
-2

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

Rebuke answered 25/3, 2015 at 15:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.