使用 ng-model 将数据插入数组



我使用 ng-repeat 渲染数组的内容,如下所示-

<tr  ng-repeat="option in eventCtrl.questionDetail.options track by $index">
<th scope="row">Option {{$index + 1}}</th>
<td>
<input type="text" ng-model="option" ng-change="eventCtrl.newlyAddedOptions[$index] = option" style="width:100%;">
</td>
<td>
<button type="button" ng-confirm-click="Are you sure to delete?" confirmed-click="eventCtrl.removeOption($index)" class="btn btn-light btn-sm">Delete</button>
</td>
</tr>
<button type="button" class="btn btn-dark" ng-click="eventCtrl.addOption()" id="addNewOption">+ Add New Answer Option</button>

单击按钮后,我将一个空字符串插入到questionDetail.options数组中,以便我得到一个空的输入字段来插入我的数据。控制器函数如下所示-

myApp.controller('eventController',function(){
let dash=this;
dash.newOption ='';
//store all newoptions to this array before finally updating the 
//question
dash.newlyAddedOptions = [];
dash.addOption = () =>{
dash.questionDetail.options.push(dash.newOption);
});
//add new options 
dash.updateTheQuestion = () =>{
//add the newly added options in the questionDetail if any which will be finally updated
apiService.updatequestion(dash.params.qid,dash.questionDetail).then(function successCallBack(response) {
$rootScope.$broadcast("loader_hide");
alert(response.data.message);
});
}

现在,当我将数据插入字段并尝试添加另一个选项时,先前插入的字段变为空白,因为questionDetail.options数组再次重新呈现。但是,我使用ng-change来收集数据并将其存储到newlyAddOptions数组中。

如何使用ng-model="option"检索的值更改推送到数组中的空字符串,以便我可以直接将它们推送到数组questionDetal.options

我知道这件好事很容易完成,我错过了一些东西。 提前谢谢你。

编辑:我正在推送一个空字符串,因为我想在单击添加选项时输入空白,我可以在其中插入新选项。这主要是编辑问题视图,用户可以在其中添加选项或删除来自数据库的选项的选项。

普伦克尔-https://plnkr.co/edit/SLfy8qaz8LoHurwpVmw6?p=catalogue

试试这个:

<tr  ng-repeat="opt in eventCtrl.questionDetail.options track by $index">
<th scope="row">Option {{$index + 1}}</th>
<td>
<input type="text" ng-model="newlyAddedOptions[$index]"  style="width:100%;">
</td>
<td>
<button type="button" ng-confirm-click="Are you sure to delete?" confirmed-click="eventCtrl.removeOption($index)" class="btn btn-light btn-sm">Delete</button>
</td>
</tr>
<button type="button" class="btn btn-dark" ng-click="eventCtrl.addOption()" id="addNewOption">+ Add New Answer Option</button>

https://codepen.io/supravi96/pen/bMmpOQ?editors=1010

最新更新