Captain Rib Captain Rib - 1 year ago 166
AngularJS Question

Dynamically add key pair value to $scope variable and bind them with label and input

I am working on an AngularJS project. I have a form where user can optionally add multiple pairs of (key, value).

Imagine the key is the label for a input box, the user can select from a dropdown list to be the value of the label (key).

The value is the value user entered in the input box. So, which means, the key and value are both dynamically decided by the user.

Here is what I have tried:

$scope.optionArray = [];
$scope.addOption = function(key, value) {
var temp = {};
temp[key] = value;

And I am using ng-repeat to display the content of optionArray in the html file.
In the html file, I have a button which can add an option to the pair like:

<button type="button"
data-ng-click="addOption(???, ???)">Add Options
<div ng-repeat="option in optionArray">
<select ng-model=option.???>
<input ng-model=option.???>

I am really confused because there are so many dynamic pieces. All ??? are the places that I don't know what to put.

In conclusion, I want the user to dynamically add a key, pair value to the form and they can edit those key-pair values however they want before the form is finally submitted. How can I do this?

Answer Source

I think you may be over-complicating this problem. It seems like all you need to do is dynamically add key/value pairs, then give yourself the option to modify both the key and the value for each and every pair before submission.

As it currently stands, your nested dropdown doesn't allow you to easily re-select an option to edit.

EDIT: Updated to use a static list of keys:

Working plunker.


<body ng-app="app">
    <div ng-controller="OptionsCtrl">
      <select ng-model=tempOption.key>
        <option ng-repeat="key in keys">{{key}}</option>

      <input type="text" ng-model="tempOption.value" />

      <button type="button" 
        data-ng-click="addOption()">Add Options
      <div ng-repeat="option in optionArray | orderBy:'key'">
        <input type="text" ng-model="option.key" />

        <input type="text" ng-model="option.value" />

      <h4>Current Data</h4>
      <div ng-repeat="option in optionArray | orderBy:'key'">
        <label ng-bind="option.key"></label>

        <label ng-bind="option.value"></label>


var app = angular.module('app', []);
app.controller('OptionsCtrl', ['$scope', function($scope) {
  $scope.tempOption = {};
  $scope.keys = ['key1', 'key2', 'key3'];
  $scope.optionArray = [];
  $scope.addOption = function() {
    var temp = {
        key: $scope.tempOption.key,
        value: $scope.tempOption.value
    $scope.tempOption = {};