Search code examples
javascriptangularjsjsoninputbox

AngularJS: Write inside input box via JS, Do not transfer the value in the JSON


Background: I have an external device (barcode reader) that sends information back to a tablet when the user scans something. I subscribe to that channel and I need the value to be inside the currently focused cell and write it there.

Bug: I can catch the subscription and write the value visually in the Input box, but it never reaches the JSON underneath. I also tried $scope.$apply() but it did not change anything (maybe I used it wrong).

"Working" Plunker with the problem

$scope.randomClickOnStuff = function() {
    // Here Randomely publish stuff with value so we can write it in specific field.
    window.setTimeout(function() {
        if (!$scope.stopMe) {
            vm.objectOtSubscribeTo.publish(channelToUse, Date.now());
            $scope.randomClickOnStuff();
        } else {
            // Stop the loop.
        }
    }, 1000);
};

var callbackCompleted = function(resultValue) {
    // Important code Here
    // Code to write in the input box here.

    console.log(resultValue);
    if (document.activeElement.localName == "input") {
        // Option 1:
        //--> Work Visually <-- but do not put the value inside the JSON.
        document.activeElement.value = resultValue;
        $scope.$apply();

        // Option 2:
        // http://stackoverflow.com/questions/11873627/angularjs-ng-model-binding-not-updating-when-changed-with-jquery
        // Problem: The "document.activeElement.attributes['ng-model'].value" is not link with the scope, but with the ng-repeat row. So I have access to the Scope, but not the Row item.
       //var binding = document.activeElement.attributes['ng-model'].value;
       // Rule: I might not know where the Item is so I cannot do $scope.complexObject[row][binding]
    } else {
        console.log("not inside a Input box.");
    }
};

vm.objectOtSubscribeTo.subscribe(channelToUse, callbackCompleted);

Thanks


Solution

  • One solution would be to keep track of the selected row and cell by setting them on focus of one of the cells

    $scope.focusedRow = false;
    $scope.focusedCell = false;
    
    $scope.setFocused = (row, cell) => {
      $scope.focusedRow = row;
      $scope.focusedCell = cell;
    };
    
    /* In callback... */
    if ($scope.focusedRow !== false && $scope.focusedCell !== false) {
      $scope.$apply(
        () => $scope.complexObject[$scope.focusedRow]
          ["cellInTheRow"][$scope.focusedCell] = resultValue
      );
    }
    
    <input type="text" ng-model="row.cellInTheRow[key]"
      ng-focus="setFocused(rowKey, key)" ng-blur="setFocused(false, false)">
    

    Example: https://plnkr.co/edit/och5PoepJuRde0oONIjm?p=preview