2

请检查这个小提琴:http: //jsfiddle.net/kgXRa/

这是代码(在 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--;
                }
            });
        }
    }
}]);

当用户创建新字段时,我需要添加删除按钮。不知何故,我需要删除计数器,以便在用户删除输入时清除数组。我曾尝试使用 jQuery,但我认为 Angular.JS 中应该有一种方法

使用我编写的脚本删除错误的脚本。

多谢你们。

4

1 回答 1

13

这是一个快速而肮脏的示例,说明如何以更“有角度的方式”完成此任务。

您的行存储为具有一对属性的单个对象数组,并且您有两个用于添加和删除行的函数。

$scope.inputs = [];

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

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

在您看来,您使用 ng-repeat 迭代对象数组,当您单击按钮时,数据会自动出现和消失。

<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>

这是一个小提琴:http: //jsfiddle.net/A6G5r/

于 2014-05-23T00:50:12.640 回答