这是我的HTML:
<body ng-app="app">
<div ng-controller="AppController as vm">
<form name="testForm" ng-submit="vm.submit(vm.message)" class="form-group">
<textarea ng-model="vm.message.text" placeholder="text" class="form-control"></textarea>
<input type="hidden" ng-model="vm.message.date">
<input type="submit" class="btn btn-primary">
</form>
<table class="table table-stripped table-bordered">
<tr ng-repeat="message in vm.messages track by $index">
<td>{{ message.text }}</td>
<td>{{ message.date }}</td>
</tr>
</table>
</div>
这是我的控制者:
(function(){
'use strict';
angular.module('app', [
'ngRoute'
]).controller('AppController', AppController);
function AppController() {
var vm = this;
vm.submit = submit;
vm.messages = [];
function submit(elem) {
elem.date = new Date();
vm.messages.push(elem);
}
}
})();
我不明白,每当我输入并提交消息对象时, vm.messages 数组中的所有对象都会成为该对象。
我想保存数组中的所有对象而不做任何更改。我究竟做错了什么?
答案 0 :(得分:4)
您只使用一个消息对象,因此您始终可以添加对它的引用。
在提交
时创建新对象
(function(){
'use strict';
angular.module('app', [
]).controller('AppController', AppController);
function AppController() {
var vm = this;
vm.submit = submit;
vm.messages = [];
vm.message = {}; //create object
function submit(elem) {
elem.date = new Date();
vm.messages.push(elem);
vm.message = {}; //create new object
}
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<div ng-app="app" ng-controller="AppController as vm">
<form name="testForm" ng-submit="vm.submit(vm.message)" class="form-group">
<textarea ng-model="vm.message.text" placeholder="text" class="form-control"></textarea>
<input type="hidden" ng-model="vm.message.date">
<input type="submit" class="btn btn-primary">
</form>
<table class="table table-stripped table-bordered">
<tr ng-repeat="message in vm.messages track by $index">
<td>{{ message.text }}</td>
<td>{{ message.date }}</td>
</tr>
</table>
</div>
答案 1 :(得分:0)
嗯,你没有在任何地方定义vm.message
?我认为也可以将提交功能存储为vm
的一部分:
(function(){
'use strict';
angular.module('app', [
'ngRoute'
]).controller('AppController', AppController);
function AppController() {
var vm = this;
vm.submit = submit;
vm.message = {};
vm.messages = [];
vm.submit = function(elem) {
elem.date = new Date();
vm.messages.push(elem);
}
}
})();