如何去除AngularJS动态表单元素? [英] How to remove an element from AngularJS dynamic form?

查看:136
本文介绍了如何去除AngularJS动态表单元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

下面是code(在实施的jsfiddle)

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--;
                }
            });
        }
    }
}]);

我需要添加删除按钮,当用户创建新的领域。不知怎的,我需要删除该计数器使阵列清理为用户删除输入。
我曾尝试使用jQuery但是我觉得应该有一个Angular.JS方式

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.

谢谢你们。

推荐答案

下面是如何,你可以在一个更角的方式完成这个一个快速和肮脏的例子。

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);
}

在你看来,你遍历你使用NG-重复对象数组,数据会自动出现,当你点击的按钮消失。

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>

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

这篇关于如何去除AngularJS动态表单元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆