How to remove an element from AngularJS dynamic fo

2019-04-12 23:04发布

问题:

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/