Javascript 将输入字段动态添加到数组中
我想动态添加输入字段,ng模型必须在下面的结构中。我还想从数组中删除项 预期的JsonJavascript 将输入字段动态添加到数组中,javascript,angularjs,json,Javascript,Angularjs,Json,我想动态添加输入字段,ng模型必须在下面的结构中。我还想从数组中删除项 预期的Json { "Animals": { "animal": [ "dog","cat","lion" ] } } 查看 <div ng-repeat="x in selected.Animals.animal"> <button ng-hide="$first" ng-click="removeChoice($inde
{
"Animals": {
"animal": [ "dog","cat","lion" ]
}
}
查看
<div ng-repeat="x in selected.Animals.animal">
<button ng-hide="$first" ng-click="removeChoice($index)">remove</button>
<input type="text" ng-model="x"/>
<button ng-show="$last" ng-click="addNewChoice(x)">addnew</button>
</div>
<body ng-app="myApp" ng-controller="myController as ctrl">
<input type="text" ng-model="ctrl.x"/>
<button ng-click="ctrl.addNewChoice(ctrl.x)" ng-disabled="!ctrl.x">addnew</button>
<div ng-repeat="s in ctrl.selected.Animals.animal">
<button ng-click="ctrl.removeChoice($index)">remove</button>
<input type="text" ng-model="s" disabled/>
</div>
<pre>{{ctrl.selected | json}}</pre>
</body>
这是您在
ng show
和ng hide
中误用了
和
。此外,如果可能,建议使用ng
首先,至少出于性能原因,您应该使用track by
进行ng repeat
。在您的情况下,添加重复的动物名称将导致违反repeater的密钥唯一性
我建议使用以下代码作为可能的解决方案
控制器
$scope.selected={};
$scope.selected.Animals= {};
$scope.selected.Animals.animal=[""];
$scope.addNewChoice = function (x) {
$scope.selected.Animals.animal.push(x);
};
$scope.removeChoice = function (index) {
$scope.selected.Animals.animal.splice(index, 1);
};
angular.module('myApp',[])
.controller('myController', function($scope){
this.x = "";
this.selected={};
this.selected.Animals= {};
this.selected.Animals.animal =[];
this.addNewChoice = function (x) {
this.selected.Animals.animal.push(x);
this.x= "";
};
this.removeChoice = function (index) {
this.selected.Animals.animal.splice(index, 1);
};
});
查看
<div ng-repeat="x in selected.Animals.animal">
<button ng-hide="$first" ng-click="removeChoice($index)">remove</button>
<input type="text" ng-model="x"/>
<button ng-show="$last" ng-click="addNewChoice(x)">addnew</button>
</div>
<body ng-app="myApp" ng-controller="myController as ctrl">
<input type="text" ng-model="ctrl.x"/>
<button ng-click="ctrl.addNewChoice(ctrl.x)" ng-disabled="!ctrl.x">addnew</button>
<div ng-repeat="s in ctrl.selected.Animals.animal">
<button ng-click="ctrl.removeChoice($index)">remove</button>
<input type="text" ng-model="s" disabled/>
</div>
<pre>{{ctrl.selected | json}}</pre>
</body>
新增
去除
{{ctrl.selected}json}
以下是问题所在如何将项目插入到上述类似json的结构中?您是否正在寻找类似的内容?是的,非常感谢。有没有办法避免数组中的空字符串?非常感谢:)