gpt4 book ai didi

javascript - 克隆表单和克隆 angularjs 中相应表单中的字段

转载 作者:行者123 更新时间:2023-12-01 03:26:00 24 4
gpt4 key购买 nike

我有一个表单,其中有一些字段和 2 个按钮,其中一个用于克隆完整表单,另一个用于仅克隆表单字段。我尝试使用 ng-repeat ,但是当我克隆表单然后尝试克隆原始表单中的字段时,它也会克隆克隆表单中的字段。如何限制复制形式的克隆。这是我的 HTML

    <!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@1.6.1" data-semver="1.6.1" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="MyController">
<div ng-repeat="form in forms">
<hr />
<form name="myForm" ng-init="name = form.name">
<br>

<div ng-repeat="user in users">
<input type="text" ng-model="user.name"/>
<input type="text" ng-model="user.phone"/>
</div><br>
<button type="button" href="" ng-click="addUser()">Add user</button>
</form>
</div>
<hr />
<input type="button" value="Create form" ng-click="createForm()" />
</div>
</body>
</html>

这是我的`script.js

    angular.module("myApp", []).controller('MyController',
['$scope', function($scope){
$scope.forms = [{name: "form1"}];
$scope.createForm = function(){
$scope.forms.push({name: "form" + ($scope.forms.length + 1)});
};
$scope.saveForm = function(formScope){
alert("Save called for " + formScope.name + ", myInputValue = " + formScope.myInputValue);
};
$scope.users = [{name: 'John',phone: '098097770'},{name: 'Alice',phone: '765876598'}];
$scope.addUser = function() {
$scope.users.push({name: 'New user',phone: ''});
};
$scope.submit = function() {
alert('Here are the users: ' + angular.toJson($scope.users));
};
}]);

Plnkr Demo

最佳答案

这是工作 plnkr: plnkr

基本上,您需要将 userform 对象链接起来,以便它对于每个表单都是唯一的。

ng-repeat(嵌套的)会有一些变化,并且 addUser 的一个函数调用将在其中传递需要添加用户的表单的索引

$scope.forms = [
{
name: "form1",
users: [
{name: 'John',phone: '098097770'},
{name: 'Alice',phone: '765876598'}
]
}
];
$scope.createForm = function(){
$scope.forms.push({
name: "form" + ($scope.forms.length + 1),
users: [
{name: 'John',phone: '098097770'},
{name: 'Alice',phone: '765876598'}
]
});
};
$scope.saveForm = function(formScope){
alert("Save called for " + formScope.name + ", myInputValue = " + formScope.myInputValue);
};

$scope.addUser = function(index) {
$scope.forms[index].users.push({name: 'New user',phone: ''});
};

关于javascript - 克隆表单和克隆 angularjs 中相应表单中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44824477/

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