I am making a web application using angularJS 1.5. The user will be interacting with the webpage using barcode scanner connected to the network. The connection itself is done through a websocket which returns me the value which was scanned.
What I would like to do is:
- Check which field has focus on the screen
- Set the value of this field to the scanned barcode
- Trigger the event for the field
This is the code I have now:
self.scannerSocket.onmessage = function (e) {
// Get the scanned barcode from the event
var obj = JSON.parse(e.data);
var message = obj.Body.Values[0].Value;
var value = message.replace(/ +(?= )/g,'');
// Get the element which has focus on the screen
var $focusedElement = $($document[0].activeElement);
if(! $focusedElement || $focusedElement.is(":disabled")) return;
// Set the new value of the element
$focusedElement.val(value);
// Trigger the enter event on the element
$timeout(function(){
var e = jQuery.Event("keypress");
e.which = 13;
e.keyCode = 13;
$focusedElement.trigger(e);
});
};
The issue is that changing the value of the element does not change the ng-model behind this element. I was thinking to do something like this:
var model = $focusedElement.attr("ng-model");
$scope[model] = value;
The issue is however that the code for the websocket is in a service. So there is no $scope
. Plus there are multiple isolated components in my application. Each with their own scope. The scanning should work on all the input fields in the screen.
So Question: how can I change the value of the ng-model behind the element?