我有一个简单的指令,在点击添加按钮后创建一个文本。 并且在点击每个指令后正确删除和销毁指令。
但我需要在选中后删除所有指令。
例如我点击添加按钮5步,结果相同
指令内容 指令内容 指令内容 指令内容 指令内容
我需要点击第2项,然后删除并销毁第3,4,5项的范围
另一个问题是,我可以通过spsephic id删除指令吗?
<body ng-app="app">
<div ng-controller="MainController">
<button ng-click="Stage()">{{stage}}</button>
<div class="my-directive-placeholder"></div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var app = angular.module('app', []);
app.controller('MainController', function($scope, $compile, $element){
$scope.stage = 'Add';
var childScope;
$scope.Stage = function(){
childScope = $scope.$new();
var el = $compile( "<b my-directive></b>" )(childScope);
$('.my-directive-placeholder').append(el);
}
})
app.directive('myDirective', function($interval){
return {
template: 'Directive content<br>',
link: function(scope, element, attrs){
element.on('click', function () {
scope.$destroy();
element.remove();
});
scope.$on('$destroy', function(){
console.log('destroid');
});
}
}
});
</script>
答案 0 :(得分:0)
相反在编译时创建html,可能最好有专门的指令,比如,看看这是否符合您的要求
angular.module('MyApp', [])
angular.module('MyApp')
.controller("DirectivePageController",
function() {
var self = this;
self.fields = [{
Name: 'Directive1'
}];
self.newField = function() {
self.fields.push({
Name: ('Directive' + (self.fields.length + 1))
});
};
self.removeField = function(field) {
var index = self.fields.indexOf(field);
if (index >= 0) {
self.fields.splice(index, 1);
}
};
})
.controller("appDirectiveController", ['$scope', '$attrs',
function($scope, $attrs) {
var self = this;
var directiveScope = $scope.$parent;
self.options = directiveScope.$eval($attrs.model);
self.onOk = function() {
alert(JSON.stringify(self.options) + ' button clicked');
}
}
])
.directive('appDirective', function($compile) {
return {
transclude: true,
template: '<div ng-click="dirCtrl.onOk()" type="">{{type|uppercase}}</div>',
scope: {
index: '@',
type: '@'
},
restrict: 'E',
replace: true,
controller: 'appDirectiveController',
controllerAs: 'dirCtrl',
}
})
&#13;
<script src="https://code.angularjs.org/1.4.8/angular.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<body>
<div ng-app="MyApp">
<div ng-controller="DirectivePageController as pageCtrl">
<span><a href="" ng-click="pageCtrl.newField()">Add Button</a></span>
<div ng-repeat="field in pageCtrl.fields track by $index">
<app-directive type="{{field.Name}}" model="field">
</app-directive>
<a href="" ng-click="pageCtrl.removeField(field)">Remove</a>
</div>
</div>
</div>
</body>
</html>
&#13;