我一直在玩角度和表格,但我在使用下面的代码时遇到了一些麻烦。我认为只要提交表单,它就应该为ng-repeat已经显示的那些添加forenames,但是提交按钮似乎什么都不做。
HTML:
<!DOCTYPE html>
<html lang="en" ng-app="file">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="bootstrap.min.css" />
<script types="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script types=text/javascript" src="formLoops.js"></script>
<title>Title</title>
</head>
<body ng-controller="PersonalDetailsController as person">
<p ng-repeat="info in person.details">{{info.forename}}</p>
<form name="PersonalDetailsForm" ng-controller="DataEntryController as dataCtrl" ng-submit="addPerson(person)">
<blockquote>
<p>{{dataCtrl.person.forename}}</p>
<p>{{dataCtrl.person.surname}}</p>
</blockquote>
<label>Forename:</label>
<input ng-model="dataCtrl.person.forename"/>
<label>Surname:</label>
<input ng-model="dataCtrl.person.surname"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
JS:
var app = angular.module("file", []);
app.controller("PersonalDetailsController", function() {
this.details = personalDetails;
});
app.controller("DataEntryController", function() {
this.person = {};
this.addPerson = function(person) {
person.personalDetails.push(this.person);
};
});
var personalDetails = [{
forename: "John",
surname: "Doe"
},
{
forename: "John",
surname: "Smith"
}
];
答案 0 :(得分:1)
您需要对代码进行两处更改
1)在HTML中,您需要添加ng-submit="dataCtrl.addPerson(person)"
因为您使用控制器作为语法
2)您需要将您的js代码更改为person.personalDetails.push(this.person);
至person.details.push(this.person);
这是因为您的重复使用了详细信息数组,因此您需要将新数据推送到详细信息数组本身。您正试图将全局数组中的数据推送到无法工作的原因
由于
答案 1 :(得分:0)
因为您在调用函数时使用controllerAs
使用controllerAs参考。比如ng-submit="dataCtrl.addPerson(person)"
<form name="PersonalDetailsForm" ng-controller="DataEntryController as dataCtrl" ng-submit="dataCtrl.addPerson(person)">
答案 2 :(得分:0)
您需要找到一种在控制器之间共享数据的方法。 其中一种方法是使用角度服务。
看看这个插头! https://plnkr.co/edit/oimKIgCDKknwsmSWbUsT?p=preview
<强>的script.js 强>
try
{
String parcel = await InputQueue.ReceiveAsync(timeSpan);
}
catch(InvalidOperationException x)
{
}
<强>的index.html 强>
var app = angular.module("file", []);
app.controller("PersonalDetailsController", function(PersonService) {
this.details = PersonService.personalDetails;
});
app.controller("DataEntryController", function(PersonService) {
this.person = {};
this.addPerson = function(person) {
PersonService.personalDetails.push(this.person);
};
});
app.service("PersonService", function() {
this.personalDetails = [{
forename: "John",
surname: "Doe"
}, {
forename: "John",
surname: "Smith"
}];
});