beingalex beingalex - 6 months ago 9
AngularJS Question

Data bind input to list element in Angular

I would like each one of my list items to be editable via the

input
. Clicking on the list item fills in the input, but how do I then specify what item to update? I have the
$watch
working.

Any help is appreciated.

I have a plunker: https://plnkr.co/edit/mslpklTaStKEdo64FpZl?p=preview

Here is the code:

<body ng-app="myApp">

<div ng-controller="MyController">

<ul ng-repeat="item in collection">
<li ng-click="edit(item.name)">{{item.name}}</li>
</ul>

<input name="myinput" ng-model="myinput" />
</div>

</body>


JS:

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

.controller('MyController', function($scope, $http) {

$scope.collection = [
{name:'foo'},
{name:'bar'},
{name:'foobar'},
{name:'barfoo'},
];

$scope.edit = function(current_name) {

$scope.myinput = current_name;

console.log(current_name);

}

$scope.$watch('myinput', function(NewValue, OldValue) {
console.log(NewValue);
}, true);

})

Answer

You need to pass the $index to edit() as well, so you know which index of the array to update later:

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

.controller('MyController', function($scope, $http) {

  $scope.collection = [
      {name:'foo'},
      {name:'bar'},
      {name:'foobar'},
      {name:'barfoo'},
    ];

  $scope.edit = function(current_name, current_index) {
    $scope.myinput = current_name;
    $scope.myindex = current_index;
  }
  
  $scope.$watch('myinput', function(NewValue) {
    if($scope.myindex) {
      $scope.collection[$scope.myindex].name = NewValue;
    }
  })

})
<script data-require="angularjs@1.5.5" data-semver="1.5.5" src="https://code.angularjs.org/1.5.5/angular.js"></script>

<div ng-app="myApp">

  <div ng-controller="MyController">
    <ul ng-repeat="item in collection">
      <li ng-click="edit(item.name, $index)">{{item.name}}</li>
    </ul>
  
    <input  name="myinput" ng-model="myinput"  />
  </div>

</div>

Passing the actual item if possible instead, as the other answers say, is preferred tho.