Unable to map element into array in input box in AngularJS

advertisements

I am new to javascript and AngularJS. I'm having a bit of difficulty understanding why I am unable to edit elements in an array.

the foll is the JSON structure:

 [
    {
"name": "Wittgenstein",
"thoughts": ["thought 1", "thought 2", "thought 3"]

},

{
"name": "King",
"thoughts": ["thought 1", "thought 2", "thought 3"]

}
  ];

the foll is the plunker: plunker

whenever I click, the 'edit' button agst a thought, I want the text to show in the corresponding textbox, and then when I click 'save edit', the edit shld show in the list.

I think I've got it all messed up in my edit() method and i am somehow unable to wrap my head around it. any help wld be appreciated.


I forked the Plunker and made some improvements to make the code more readable, in particular making the edit state more transparent and hiding editing controls when not in edit mode.

The main problems were:

  • Not managing editing state clearly.
  • Not referring to the correct index in the outer ng-repeat $parent.$index is required.

Hope it helps.

Plunker Here Code Below:

view.html

<body ng-controller="demoController">
    editing {{editing}}
    <div ng-repeat="classified in classifieds">
      <h1>{{classified.name }}</h1>
      <ul>
        <li ng-repeat="thought in classified.thoughts">
          {{ thought }} <button ng-click="remove(classified, $index)">Remove</button><button ng-click="edit($parent.$index, $index)">Edit</button>
        </li>
      </ul>
      <div ng-show="editing[$index].editing">
        <input type="text" ng-model="editing[$index].thought">
        <button type="submit"  ng-click="save($index)">Save</button>
      </div>
    </div>

Controller.js

// Code goes here
var app = angular.module('app', []);

app.controller('demoController', function($scope) {

  $scope.input = [];
  $scope.editing = {};

  $scope.classifieds = [
    {
"name": "Wittgenstein",
"thoughts": ["thought 1", "thought 2", "thought 3"]

},

{
"name": "King",
"thoughts": ["thought 1", "thought 2", "thought 3"]

}
  ];

  /* Add */

  $scope.save = function(classifiedIndex) {
    var editingMeta = $scope.editing[classifiedIndex];
    var thoughtIndex = editingMeta.thoughtIndex;
    $scope.classifieds[classifiedIndex].thoughts[thoughtIndex] = editingMeta.thought;
    delete $scope.editing[classifiedIndex];
  }

  /* Remove*/

  $scope.remove = function(classified, i) {
    $scope.classified.thoughts.splice(i, 1);
  }

  /* Edit */

  $scope.edit = function(classifiedIndex, thoughtIndex) {
    var classified = $scope.classifieds[classifiedIndex];
    $scope.editing[classifiedIndex] = {
      editing: true,
      thoughtIndex: thoughtIndex,
      thought: classified.thoughts[thoughtIndex]
    }
  }

});