How to remove an element from AngularJS dynamic form?

自古美人都是妖i 提交于 2019-12-13 12:14:32

问题


Please check this Fiddle: http://jsfiddle.net/kgXRa/

Here is the code (Implemented in the JSFiddle)

var app = angular.module('myApp', []);

app.controller('MyCtrl', ['$scope', function ($scope) {
    $scope.field = [];
    $scope.value = [];
    $scope.inputCounter = 0;
}]);

app.directive('addInput', ['$compile', function ($compile) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.find('button').bind('click', function () {
                var input = angular.element('<div><input type="text" ng-model="field[' + scope.inputCounter + ']"><input type="text" ng-model="value[' + scope.inputCounter + ']"> <a href="javascript:;" ng-click="remove_it(' + scope.inputCounter + ')">remove</a></div> ');

                var compile = $compile(input)(scope);
                element.append(input);
                scope.inputCounter++;
                scope.remove_it = function(scope_counter) {
                   compile.remove(this);
                   scope.inputCounter--;
                }
            });
        }
    }
}]);

I need to add the remove button when user creates the new fields. Somehow I need to drop the counter so the Array is cleared up as user delete the input. I have tried to use jQuery however I think there should be a way in Angular.JS

With the script I wrote it remove the wrong one.

Thanks guys.


回答1:


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/



来源:https://stackoverflow.com/questions/23819116/how-to-remove-an-element-from-angularjs-dynamic-form

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