数据绑定输入到Angular中的列表元素

时间:2016-06-06 15:33:49

标签: angularjs

我希望我的每个列表项都可以通过input进行编辑。单击列表项会填写输入,但如何指定要更新的项目?我有$watch工作。

感谢任何帮助。

我有一个掠夺者:https://plnkr.co/edit/mslpklTaStKEdo64FpZl?p=preview

以下是代码:

<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);  

})

3 个答案:

答案 0 :(得分:3)

更改您的代码以执行此操作

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

在您的控制器中

$scope.edit = function(item) 
{
    $scope.selectedItem = item;
}

最后回到你的标记

<input  name="myinput" ng-model="selectedItem.name"  />

这样做是将当前可编辑的项目切换为您点击的任何项目,然后当您单击它时,无论您在输入中输入什么内容都将更新该项目。

答案 1 :(得分:2)

不是传递edit(item.name),而是传递项目本身。然后angular会为你处理剩下的,不需要$ watch或$ index

<body ng-app="myApp">

  <div ng-controller="MyController">

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

   <input  name="myinput" ng-model="myinput.name"  />
  </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_item) {

  $scope.myinput = current_name;

  console.log(current_name);

}

})

答案 2 :(得分:0)

您还需要将$index传递给edit(),以便您知道稍后要更新的数组索引:

&#13;
&#13;
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;
    }
  })

})
&#13;
<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>
&#13;
&#13;
&#13;

如果可能的话,传递实际的item,正如其他答案所说的那样,是首选。