我想动态添加输入字段,ng-model必须在以下结构中。我还想从数组中删除项目。
预期Json
{
"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>
控制器
$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);
};
以下是workarea
答案 0 :(得分:1)
您误导了$first
和$last
与ng-show
和ng-hide
。此外,如果可能,建议使用ng-if
。
首先,您应该track by
使用ng-repeat
至少出于性能原因。在您的情况下,添加重复的动物名称将导致违反转发器的关键唯一性。
我建议将以下代码作为可能的解决方案
<强>控制器强>
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);
};
});
查看强>
<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>
以下是JSBin