Angularjs 使用指令动态添加和删除元素 [英] Angularjs dynamically adding and removing elements using directive
问题描述
我使用指令来创建联系表单.最初我创建 customerForm 指令来显示客户表单.在那种形式中,我有一个按钮,当我们点击添加按钮时,调用 getData 函数,该函数在内部使用 newDirective 来显示 ul 列表.为此,我使用 $compile api 来编译 html 代码.这很好,当我们点击删除按钮时,它还会显示列表值和删除按钮,它被称为 scope.remove() 函数.但它只删除那些.之后我无法删除任何元素(即按钮).我不知道为什么会这样.请帮我.jsfiddle
index.html
<客户表单></客户表单>
app.js
angular.module('sanshaApp', []).directive('newDirective', function ( $compile ){返回 {限制:'E',模板:''+'- {{这里的值}}' +'<button ng-click="remove()">移除</button>'+'</li>'+'</ul>',链接:函数(范围、元素、属性){//点击删除按钮时调用scope.remove = 函数 () {element.remove();}}}}).directive('customerForm', function($compile) {返回 {范围: {},限制:'E',转置:真实,templateUrl: "../../views/customer-form.html",控制器:mainCtrl",链接:函数(范围,元素,属性,mainCtrl){scope.getData = function() {//创建新元素 new-directive$newDirective = angular.element('
');element.append($newDirective);//编译html DOM$compile( $newDirective )(scope);}}}}).controller("mainCtrl", ['$scope', function($scope) {}])
客户表单.html
<label for="name" class="col-lg-2 form-control-label">客户名称</label><div class="col-lg-4"><input type="text" class="form-control" ng-model="name.aa" placeholder="客户名称"><label for="email" class="col-lg-2 form-control-label">电子邮件地址</label><div class="col-lg-4"><input type="email" class="form-control" ng-model="name.email" placeholder="Email">
<div class="form-group row"><div class="col-lg-4"><button class="btn btn-default" value="add" ng-click="getData()"><span class="glyphicon glyphicon-plus"></span>按钮>