Update AngularJS models from jQuery plugin with "on change" callback

I am building a web application for a touch screen computer that needs an on-screen keyboard, and I'm trying to use this excellent (or at least the only one I could find, it wasn’t scary) keyboard. https://github.com/Mottie/Keyboard/

The problem is that, as you might have guessed, the model does not update when using the on-screen keyboard. This is my code that seems to work, but it's all kind of ugly:

Partial HTML:

<input type="text" class="keyboard" ng-model="newUser.name"> <input type="text" class="keyboard" ng-model="newUser.email> 

Initializing the keyboard using the partial page controller:

 $('.keyboard') .keyboard({ stickyShift: false, usePreview: false, autoAccept: true, change: function(e, kb, el) { $scope.newUser.name = el.value; } }); 

So, with the change caused by the jQuery plugin, I can start something. Obviously, this only works when updating one field / model, one name (while email does not work at all and overwrites the name field), I need to have any number of fields updated when used with the keyboard, but fix it. How can I solve this in a less scary and not hard (if possible, and not too complicated) way?

+8
javascript jquery dom angularjs on-screen-keyboard
source share
2 answers

The way to write to Angular is to write a directive. You can set a directive with a specific class name.

So your directive will look something like this:

 app.directive('keyboard',function(){ return { require : '?ngModel', restrict : 'C', link : function(scope,element,attrs,ngModelCtrl){ if(!ngModelCtrl){ return; } $(element).keyboard({ stickyShift: false, usePreview: false, autoAccept: true, change: function(e, kb, el) { ngModelCtrl.$setViewValue(el.value); } }); } }; }); 

Now, if any element has a keyboard class and ng-Model, then your keyboard should pop up. Hope this helps.

+12
source share

I made a modification to the ganraj directive. Now the model is updated every time the keyboard button is pressed.

 app.directive('keyboard',function(){ return { require : '?ngModel', restrict : 'C', link : function(scope,element,attrs,ngModelCtrl){ if(!ngModelCtrl){ return; } $(element).keyboard({ stickyShift: false, usePreview: false, autoAccept: true, change: function(e, kb, el) { if(!scope.$$phase && !scope.$root.$$phase) { scope.$apply(function(){ ngModelCtrl.$setViewValue(el.value); }); } } }); } }; }); 
+2
source share

All Articles