javascript - AngularJS:通过JS在输入框内写入,不传输JSON中的值

标签 javascript angularjs json inputbox

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

错误:我可以捕获订阅并在输入框中直观地写入值,但它永远不会到达下面的 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

关于javascript - AngularJS:通过JS在输入框内写入,不传输JSON中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35496118/

相关文章:

angularjs - 如何使用 AngularFire 将图像上传到 firebase?

javascript - 尝试在 https ://api. thetvdb.com/向 TVDB REST API 发出 JSON POST 请求,但收到 CORS 错误

JavaScript:永不丢失绑定(bind)的方法

Javascript 为什么当第一个值为 0 时 array.slice() 不起作用?

javascript - 服务中的 Angular JS promise 不更新 View

json - Azure 认知服务技能不保留自定义技能值

json - 使用 Powershell invoke-restmethod 和 json 响应

javascript - jquery ajax调用重定向到命名url而不是相同的模板

php - 原型(prototype)和显示 :none

javascript - 如何正确绑定(bind)到 AngularJS 中的服务属性?