gpt4 book ai didi

javascript - 如何在 angularJS 中创建对象数组

转载 作者:行者123 更新时间:2023-11-28 17:24:10 25 4
gpt4 key购买 nike

我有几个输入字段,例如“标题”“名字”“姓氏”和“日期”,我将其数据存储在对象中,但我想为此数据创建一个对象数组,以便每次单击提交按钮应将新对象推送到数组中。

<!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);
}
})

最佳答案

您错过了用户的 $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);
}
})

关于javascript - 如何在 angularJS 中创建对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51969000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com