我使用指令创建联系表单。最初我创建了customerForm指令来显示客户表单。在那种形式我有一个按钮,当我们点击添加按钮,称为getData函数,该函数内部使用newDirective显示ul列表。因为我使用$ compile api来编译html代码。这很好,它还显示列表值和删除按钮当我们点击删除按钮,它的名为scope.remove()函数。但它只删除了一些。之后,我无法删除任何元素(即按钮)。我不知道为什么会发生这种情况。请帮我。 jsfiddle
<div class="container">
<customer-form></customer-form>
</div>
angular.module('sanshaApp', [])
.directive('newDirective', function ( $compile ){
return {
restrict: 'E',
template:
'<ul>' +
'<li>{{somoe value here}}' +
'<button ng-click="remove()">Remove</button>' +
'</li>'+
'</ul>',
link: function (scope, element, attributes) {
//called when click on Remove button
scope.remove = function () {
element.remove();
}
}
}
})
.directive('customerForm', function($compile) {
return {
scope: {
},
restrict: 'E',
transclude: true,
templateUrl: "../../views/customer-form.html",
controller: "mainCtrl",
link: function(scope, element, attrs, mainCtrl) {
scope.getData = function() {
//create new element new-directive
$newDirective = angular.element('<new-directive>');
element.append($newDirective);
//compile html DOM
$compile( $newDirective )(scope);
}
}
}
})
.controller("mainCtrl", ['$scope', function($scope) {
}])
<div class="form-group row">
<label for="name" class="col-lg-2 form-control-label">Customer name</label>
<div class="col-lg-4">
<input type="text" class="form-control" ng-model="name.aa" placeholder="customer name">
</div>
<label for="email" class="col-lg-2 form-control-label">Email address</label>
<div class="col-lg-4">
<input type="email" class="form-control" ng-model="name.email" placeholder="Email">
</div>
</div>
<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>
</button>
</div>
</div>
答案 0 :(得分:4)
我解决了你的问题。您的问题是指令new-directive
没有isolate
范围。
jsfiddle上的实例。
angular.module('app', [])
.controller("mainCtrl", ['$scope', function($scope) {
}])
.directive('newDirective', function($compile) {
return {
restrict: 'E',
replace: true,
scope: {},
template: '<ul>' +
'<li>' +
'<button ng-click="remove()">Remove {{ind}}</button>' +
'</li>' +
'</ul>',
link: function(scope, element, attributes) {
scope.ind = Math.round(Math.random() * 100);
scope.remove = function() {
console.log(scope.ind);
element.remove();
}
}
}
})
.directive('customerForm', function($compile) {
return {
scope: {},
restrict: 'E',
transclude: true,
template: '<div>' +
'<input type="button" value="addd" name="AAA" ng-click="getData()">' +
'</div>',
controller: "mainCtrl",
link: function(scope, element, attrs, mainCtrl) {
scope.getData = function() {
$newDirective = angular.element('<new-directive>');
element.append($newDirective);
$compile($newDirective)(scope);
}
}
};
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<customer-form></customer-form>
</div>
&#13;