简体   繁体   English

如何在Angular JS中将项目推送到对象?

[英]How do you push items to an object in Angular JS?

I am trying to push data to a ng-object after filling and submitting an html form with user defined values. 我试图用用户定义的值填充并提交html表单后将数据推送到ng-object After pressing on submit, values are pushed, but with duplicated data. 按下提交后,将推送值,但包含重复的数据。

I tried clearing $scope.user > $scope.user=''; 我试图清除$scope.user > $scope.user='';

I tried clearing the input boxes after submit. 我尝试在提交后清除输入框。

NG code below NG代码如下

var app = angular.module('ngpractice', []);

app.controller("formWorking", function($scope){
$scope.data = [];
$scope.update = function(){
    //$scope.data = angular.copy(user); 
    $scope.data.push($scope.user)
}
$scope.reset = function(){
    $scope.data = [];
    console.log('Data Wiped !')
}
});

html code HTML代码

<div ng-controller="formWorking">
<h2>Working with Forms</h2>
<form>
<fieldset id="myForm">
Name: <input type="text" name="firstname" ng-model="user.firstname"/>
Last Name: <input type="text" name="lastname" ng-model="user.lastname"         
                  required</>
<br>
Gender M: <input type="radio" name="gender" value="male" ng-model="user.gender"/>
Gender F: <input type="radio" name="gender" value="female" ng-model="user.gender" />
<input type="button" value="save" ng-click="update()"/>
<input type="button" value="reset" ng-click="reset()"/>
</fieldset>
</form>

$scope.data = []; should display different objects provided by form after submitting. 提交后应显示表单提供的不同对象。

Push a copy to the array: 将副本推送到阵列:

$scope.update = function(){
    //$scope.data = angular.copy(user); 
    ̶$̶s̶c̶o̶p̶e̶.̶d̶a̶t̶a̶.̶p̶u̶s̶h̶(̶$̶s̶c̶o̶p̶e̶.̶u̶s̶e̶r̶)̶
    var copy = Object.assign({}, $scope.user)
    $scope.data.push(copy);
}

For more information, see 有关更多信息,请参见

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM