背景:我有一个外部设备(条形码读取器),当用户扫描某些内容时,该设备会将信息发送回平板电脑。我订阅了该频道,我需要将该值放入当前关注的单元格中并将其写入那里。

错误:我可以捕获订阅并在“输入”框中直观地写入值,但是它永远不会到达下面的JSON。
我也尝试了$scope.$apply(),但是它并没有改变任何东西(也许我用错了)。

"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);


谢谢

最佳答案

一种解决方案是通过将选定的行和单元格设置为某个单元格的焦点来跟踪它们

$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)">


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

09-30 14:53
查看更多