-1

I have some inputs, and I want to get data in order of insertion, for example:
if I insert the value bbb then the value aa I want to get bbb befor aa
I search in the net and find that this order is ensured using Mapbut I don't know how to use it with ng-model.
thank you in advance.
EDIT
I'm using an object that store the value of the inputs and a customized key passed with value
here is an example, if you insert the values in input 3 then 2 then 1, and click ok, in the console the output will be ordered in an alphabetic order

aName
  • 2,751
  • 3
  • 32
  • 61

3 Answers3

1

JavaScript Object properties have no guaranteed order, see this answer.

Try using an array instead.

Community
  • 1
  • 1
Christian Zosel
  • 1,424
  • 1
  • 9
  • 16
  • I have seen that question, but how can I use an array, taking into account that my keys are not integer – aName Nov 28 '16 at 16:42
1

As stated by @czosel, javascript objects are not ordered, and are usually sorted by alphabetical order of the keys. Therefore, your best solution is probably going to involve going beyond using the ng-model directive as is.

Here are two possibilities you could try out:

Solution 1

In every <input /> place an ng-blur directive that will determine the input's order. For instance:

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++;
    }
  };
}]);

Solution 2

Store the values in an array. Similar to the first solution, but instead of keeping count, you would forego the ng-model altogether and manually add the value to an array (after checking that it doesn't already exist, which gets a little tricky with an array). Of course you also have to handle updates yourself, so the first method is definitely going to be simpler. The lodash library will probably be of much help if for some reason you decide to choose this approach.

Lots of luck!

ygesher
  • 1,133
  • 12
  • 26
0

You can Queue(First in First Out) to get data in the order of insertion. Trigger a function and store the values binded in ng-model into queue.

Ex: ng-model = data // here data will be bbb

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

if user enters aa then again bind function needs to be called to push the value inside queue U can get the values in the order of insertion.

Ajaykumar
  • 416
  • 3
  • 16