将数组传递到ng-click函数中

3

http://jsfiddle.net/u0jzkye1/

<div ng-app ng-controller="MyCtrl">
    <ul>
        <li ng-repeat="item in items">{{item.name}}</li>
    </ul>
    <button type="submit" ng-click="send()">
    Send
    </button>
</div>

当按钮不在ng-repeat中时,我如何将我的项ID传递到ng-click函数中?

你需要通过点击发送哪个id?如果它是动态的,那么你将不得不在ng-repeat本身中绑定它。否则,你可以将其作为静态值传递。 - Roy M J
2个回答

1

好的,items 已经在您的 ng-repeat 中被使用并存在于 $scope 中。因此,您只需要简单地使用 ng-click="send(items)" 即可。


这是完全正确的。事实上,处理控制器范围内保留状态的事件很少需要接收参数。 - Sombriks

0

var items = [{
  id: 1,
  name: "one"
}, {
  id: 2,
  name: "two"
}];

function MyCtrl($scope) {
  $scope.items = items;

  $scope.send = function() {
    //get items' id
    $scope.items.forEach(function(item){
      alert(item.id);
    }, this);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="MyCtrl">
  <ul>
    <li ng-repeat="item in items">{{item.name}}</li>
  </ul>
  <button type="submit" ng-click="send()">
    Send
  </button>
</div>


我知道forEach,但是this是什么? - Jennifer
@Jennifer 在forEach()中提供thisArg参数,当调用回调函数时,会将其传递给回调函数,作为其this值使用。 - 0xdw
@Jennifer 从这里阅读文档:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach - 0xdw

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接