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

时间:2019-06-20 21:11:23

标签: javascript html angularjs

我正在尝试使用用户定义的值填写并提交html表单后,将数据推送到ng-object。按下提交后,将推送值,但包含重复的数据。

我尝试清除$scope.user > $scope.user='';

我尝试在提交后清除输入框。

下方的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代码

<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 = [];在提交后应显示表单提供的不同对象。

1 个答案:

答案 0 :(得分:0)

将副本推送到数组:

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

有关更多信息,请参见