我只有几个输入字段,例如“标题”,“名字”,“姓氏”和“日期”,我将其数据存储在对象中,但我想为此数据创建对象数组,因此每次单击提交按钮,应将新对象推入数组。
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Angular Basic</title>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.8/angular-material.min.css">
</head>
<body ng-controller="myCtrl">
<form>
<md-input-container>
<label>Title</label>
<input ng-model="user.title">
</md-input-container>
<md-input-container>
<label>First Name</label>
<input ng-model="user.first_name">
</md-input-container>
<md-input-container>
<label>Last Name</label>
<input ng-model="user.last_name">
</md-input-container>
<md-input-container>
<label>Enter date</label>
<md-datepicker ng-model="user.submissionDate"></md-datepicker>
</md-input-container>
<md-button class="md-raised md-warn" ng-click="saveData()">Submit</md-button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-animate.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-aria.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.8/angular-material.min.js"></script>
<script src="app.js"></script>
</body>
</html>
JS文件:
var app = angular.module('myApp', ['ngMaterial']).controller('myCtrl', function ($scope) {
$scope.user = {}
var userArr = [];
$scope.saveData = function () {
console.log("user", $scope.user)
userArr.push(user);
console.log(userArr);
}
})
答案 0 :(得分:2)
您错过了用户的$scope
。
var app = angular.module('myApp', ['ngMaterial']).controller('myCtrl',
function ($scope) {
$scope.user = {}
var userArr = [];
$scope.saveData = function () {
console.log("user", $scope.user)
userArr.push($scope.user)
console.log(userArr);
}
})