【问题标题】:Angularjs: How do I get the item in a list when using ngChange?Angularjs:使用ngChange时如何获取列表中的项目?
【发布时间】:2014-05-12 13:33:33
【问题描述】:

我正在尝试获取这个小示例中刚刚更改的项目,我应该使用某种上下文吗?我希望它会像引用 $this 一样简单,但这似乎不起作用。

<html ng-app>
<head>
<script src="https://code.angularjs.org/1.2.9/angular.min.js"></script>
<script>
  function myController($scope) {
    $scope.items = [
      { id: 1, name: "First" },
      { id: 2, name: "Second" },
      { id: 3, name: "Third" }
    ];

    $scope.test = function() {
        // How do I get the object in the list related to the change i did?
        // I.e. "{ id: 2, name: "Second" }" for the second item.
    };
  }
</script>
</head>
<body>
<div ng-controller="myController">
<table>
  <tbody ng-repeat="item in items">
    <tr>
      <td>{{ item.id }}</td>
      <td><input type="text" ng-model="item.name" ng-change="test()"/></td>
    </tr>
  </tbody>
</table>
</div>
</body>

【问题讨论】:

  • 看到这个question
  • ng-change="test(item)" 怎么样
  • @MichaelLo 谢谢!我不敢相信我错过了!对不起这个愚蠢的问题:(

标签: javascript angularjs angularjs-ng-change


【解决方案1】:

看看这个

Working Demo

html

<div ng-app='myApp' ng-controller="myController">
<table>
  <tbody ng-repeat="item in items">
    <tr>
      <td>{{ item.id }}</td>
      <td><input type="text" ng-model="item.name" ng-change="test(item.name)"/></td>
    </tr>
  </tbody>
</table>
</div>

脚本

var app = angular.module('myApp', []);
app.controller('myController', function ($scope) {
    $scope.items = [
      { id: 1, name: "First" },
      { id: 2, name: "Second" },
      { id: 3, name: "Third" }
    ];

    $scope.test = function(item) {
        alert(item);
    };
});

【讨论】:

  • 我也看到了@MichaelLo 的评论。感谢你们俩!不敢相信我错过了... :)
  • 我不能投票给低代表(这是我的第一个问题)。我只能接受它作为回答!
猜你喜欢
  • 1970-01-01
  • 2014-06-24
  • 2015-03-13
  • 2017-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多