ziz194 ziz194 - 2 months ago 10
Javascript Question

Binding input fields to Array in Angularjs

i have this simple problem that i can't really found a solution for it. so what i am willing to do is inserting to an array values from inputs.

so for example i have this empty array at my controller first :

$scope.contents = [
{name: "", value: ""}
] ;


and i have three input fields that each of them has a label and a value :

<label>1st Label</label>
<input type='text' value='1st Value' />

<label>2nd Label</label>
<input type='text' value='2nd Value' />

<label>3rd Label</label>
<input type='text' value='3rd Value' />


i want by clicking a button to add the label and the value of each input to the array and i want the ng-model name of the values and labels to be generated automatically so in the ng-model i want to put something like this
ng-model=val[$index]
that iterates

so the result should be

$scope.contents = [
{label: "1st Label", value: "1st Value"},
{label: "2nd Label", value: "2nd Value"},
{label: "3rd Label", value: "3rd Value"}
] ;


Any help will be appreciated

Answer

Given this HTML:

  <body ng-controller="MyController">
    <label ng-repeat-start="label in labels">Label {{label}}</label>
    <input ng-model='values[$index]' type='text' value='' />
    <br ng-repeat-end>

    <button ng-click="saveEverything()">Save</button>
  </body>

And assuming you have a variable named myApp that has your main application, you'd make a controller like this:

var myApp = angular.module('app', []);

myApp.controller('MyController', function($scope, $log) {
  $scope.labels = ['one', 'two', 'three'];
  $scope.values = new Array($scope.labels.length);

  $scope.saveEverything = function() {
    $scope.contents = [];
    for (i = 0; i < $scope.labels.length; i++) {
      $scope.contents.push({
        label: $scope.labels[i],
        value: $scope.values[i]
      });
    }
    $log.info('Saved to array[0]: ' + $scope.contents[0].value);
    $log.info('Saved to array[1]: ' + $scope.contents[1].value);
    $log.info('Saved to array[2]: ' + $scope.contents[2].value);
  }
});

Demo: http://plnkr.co/edit/JCCa1f?p=preview (Use your browser's Javascript console to see the values placed in the array)

That will wipe the $scope.contents array each time you press Save and then place three objects in it, one for each of your inputs.

I'm not sure why you'd want to do this, though, so if this isn't what you are looking for, perhaps you could expand on your question a bit to make your problem and needs a bit more clear.