How to remove an element from AngularJS dynamic form?

試著忘記壹切 提交于 2019-12-04 17:21:36

Here is a quick and dirty example of how you could accomplish this in a more "Angular way".

Your rows are stored as a single array of objects having a pair of properties, and you have two functions for adding and removing rows.

$scope.inputs = [];

$scope.addInput = function(){
    $scope.inputs.push({field:'', value:''});
}

$scope.removeInput = function(index){
    $scope.inputs.splice(index,1);
}

In your view, you iterate over your array of objects using ng-repeat and the data automatically appears and disappears as you click the buttons.

<div ng-app="myApp" ng-controller="MyCtrl">
    [<span ng-repeat="input in inputs">"{{input.field}}"</span>]:
    [<span ng-repeat="input in inputs">"{{input.value}}"</span>]
    <div ng-repeat="input in inputs">
        <input type="text" ng-model="input.field" />
        <input type="text" ng-model="input.value" />
        <button ng-click="removeInput($index)">Remove</button>
    </div>
    <button ng-click="addInput()">add input</button>
</div>

Here's a Fiddle: http://jsfiddle.net/A6G5r/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!