我遇到与this question相同的问题,但那里的解决方案对我不起作用。
我正在学习AngularJS,而我正在努力使用ng-model
内的ng-repeat
提交表单数据。我有一个小组成员名单和他们上次参加的日期:
[{"name": "Bob", "attended": "01/01/16"},
{"name":"Steve", "attended": "02/01/16"}]
我列出了使用ng-repeat
的所有成员,并且希望能够更新"参加过的"每行中一个表单的字段。但是,我无法参加"正确绑定。这是代码:
<div ng-repeat="member in members">
{{member.name}}
<input type="text" ng-model="attended"></input>
<a href="#" ng-click="setAttended(attended)">Save</a>
</div>
$scope.setAttended = function(attended){
alert( 'Date: ' + attended);
};
警报显示&#34;日期:未定义&#34;。我也尝试过使用对象而不是原语:
<div ng-repeat="member in members">
{{member.name}}
<input type="text" ng-model="member.attended"></input>
<a href="#" ng-click="setAttended(member)">Save</a>
</div>
$scope.setAttended = function(member){
alert( 'Date: ' + member.attended);
};
我得到ng-repeat
将为每个对象创建一个新范围,这些范围从父范围继承setAttended
。我知道父作用域不知道子作用域中发生了什么,所以参数必须让它知道。
为什么我的参数不包含我的输入值?
在运行setAttended
之前输入是否未正确绑定到模型?
答案 0 :(得分:0)
请尝试以下代码并反馈我:
<div ng-repeat="member in members">
{{member.name}}
<input type="text" ng-model="members[$index].attended"></input>
<a href="#" ng-click="setAttended(members[$index].attended)">Save</a>
</div>
$scope.setAttended = function(attended){
alert( 'Date: ' + attended);
};
答案 1 :(得分:0)
使用this
,它指的是scope
函数中正确的ng-repeat
对象
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.members = [{"name": "Bob", "attended": "01/01/16"},
{"name":"Steve", "attended": "02/01/16"}];
$scope.setAttended = function(member){
alert( 'Date: ' + this.attended);
};
});
<script data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js" data-require="angular.js@1.4.x"></script>
<body ng-app="plunker" ng-controller="MainCtrl">
<div ng-repeat="member in members">
{{member.name}}
<input type="text" ng-model="attended">
<a href="#" ng-click="setAttended(member)">Save</a>
</div>
</body>
答案 2 :(得分:0)
实际上它对我有用。请参阅下面的代码段。
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.9/angular-route.min.js"></script>
<style>
</style>
</head>
<body ng-controller="myController">
<div ng-repeat="member in members">
{{member.name}}
<input type="text" ng-model="member.attended"/>
<a href="#" ng-click="setAttended(member)">Save</a>
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myController", function($scope) {
$scope.members = [{
"name": "Bob",
"attended": "01/01/16"
}, {
"name": "Steve",
"attended": "02/01/16"
}];
$scope.setAttended = function(member) {
alert('Date: ' + member.attended);
}
});
</script>
</body>
</html>
&#13;