Stephan K.
Stephan K.

Reputation: 15732

Save key, value of model does not get saved in scope and duplicates input fields

This is my model:

{ aktuell: { N5: '8', Auftragsnr: 123 },
  historie:
   [
    { some data },
    { more data }
   ]
};

I have this html code:

 <ul>
 <li>
        <span ng-repeat="(key, value) in friends[0].aktuell" ng-show="key != '_id' && key != '__v'">
            {{key}}    
        </span>
 </li>
 <br>
 <li ng-repeat="friend in friends">
        <span ng-repeat="(key, value) in friend.aktuell" ng-show="key != '_id' && key != '__v'">
            <input type="text" ng-model="value">
        </span>
        <button ng-click="save(friend)" class="btn btn-primary">Save</button>
  </li>
  </ul>

What happens:

When I click on Save, the controller gets correctly fired (and does API requests, etc), however any new value entered into the input field does not get saved inside the friend model (scope). I tried Chrome Batarang, and when entering a value a new input field, the scope is not changed, see screenshot:

enter image description here

Expected Behaviour:

The expected behaviour is to save the new "N5" value inside the "aktuell" member of the friend model.

Update: Fixed the "double input" field error in the meanwhile

Upvotes: 0

Views: 326

Answers (2)

Yogesh Mangaj
Yogesh Mangaj

Reputation: 3280

Change ng-model="value" to friend.aktuell[key]

The variable value is not referencing the '8' of "N5" in your "friend.aktuell" object, but instead it is a "copy" of it because '8' or '123' or 'test' is a string/number (immutable primitives) and not an object (mutable object).

Assignment to immutable primitives are not references (in Javascript strings are also considered to be immutable primitives).

key, value are scope variables that Angular creates internally when you use ng-repeat within the scope that each repeated item (span in you example) gets of its own.

To illustrate, assume that ng-repeat simply does the following,

for (var k in friend.aktuell) {
  if (friend.aktuell.hasOwnProperty(k)) {
    var key = k;
    var value = friend.aktuell[k];
  }
}

Here modifying value will update friend.aktuell[k] only if friend.aktuell[k] is a mutable object.

Upvotes: 0

dhavalcengg
dhavalcengg

Reputation: 4713

Try this

 <li ng-repeat="friend in friends">
        <span ng-repeat="(key, value) in friend.aktuell" ng-show="key != '_id' && key != '__v'">
            <input type="text" ng-model="friend.aktuell[key]">
        </span>
        <button ng-click="save(friend)" class="btn btn-primary">Save</button>
  </li>

Upvotes: 2

Related Questions