如何按插入顺序将值绑定到对象

how to bind values to an object in order of insertion

我有一些输入,我想按插入顺序获取数据,例如:
如果我插入值 bbb 那么我想要的值 aaaa
之前获得 bbb 我在网上搜索,发现使用 Map 可以确保此顺序,但我不知道如何使用 ng-model.
先感谢您。
编辑
我正在使用一个对象来存储 inputs 的值和一个自定义的 key 传递值
这是一个 example,如果您在输入 3 然后 2 然后 1 中插入值,然后单击确定,在控制台中输出将按字母顺序排列

JavaScript 对象属性没有保证顺序,请参阅 this answer

尝试使用数组。

如@czosel 所述,javascript 对象未排序,通常按键的字母顺序排序。因此,您最好的解决方案可能是超越按原样使用 ng-model 指令。

您可以尝试以下两种可能性:

解决方案 1

在每个 <input /> 中放置一个 ng-blur 指令来确定输入的顺序。例如:

HTML <input ng-blur="onBlur('model1')" ng-model="model1" /> <input ng-blur="onBlur('model2')" ng-model="model2" />

controller.js

app.module('myModule').controller('myCtrl', ['$scope', function($scope) {
  $scope.count = 0;

  $scope.onBlur = function(key){
    // check if anything was entered
    if($scope[key]){

      // make sure this is first time data was entered into this input
      if(!$scope[key].order)
        $scope[key].order = $scope.count++;
    }
  };
}]);

解决方案 2

将值存储在数组中。与第一个解决方案类似,但不是保持计数,而是完全放弃 ng-model 并手动将值添加到数组(在检查它不存在之后,这对数组来说有点棘手) .当然你也必须自己处理更新,所以第一种方法肯定会更简单。如果出于某种原因您决定选择这种方法,lodash 库可能会有很大帮助。

祝你好运!

您可以使用队列(先进先出)来按插入顺序获取数据。触发一个函数并将在 ng-model 中绑定的值存储到队列中。

Ex: ng-model = data // 这里的数据是 bbb

var queue = [];
function bind(value){
queue.push(value); // value will be bbb       
}

如果用户输入 aa 则需要再次调用绑定函数以将值推送到队列中 你可以按插入顺序获取值。