Slimshadddyyy Slimshadddyyy - 4 months ago 23
AngularJS Question

AngularJS - Remove an element created using $compile (Directive)

Directive

myApp.directive('vlcControls', function ($compile, $rootScope,$timeout) {
var linker = function (scope, element, attrs) {
$timeout(function () {
var vlcPlayerTemplate =
'<button class="btn btn-default btn-sm margin-r-10 text-center"><i class="fa fa-backward"></i></button>'+
'<button class="btn btn-default btn-sm margin-r-10 text-center"><i id="play-pause" class="fa fa-play"></i></button>'+
'<button class="btn btn-default btn-sm margin-r-10 text-center"><i class="fa fa-forward"></i></button>';
element.html(vlcPlayerTemplate);
$compile(element.contents())(scope);
});
};
return {
restrict: "E",
replace: true,
link: linker
};
});


Ctrl

this.myService = function (pictureboxIndex) {
angular.element(document.querySelector('#cameraControls')).append($compile("<vlc-controls></vlc-controls>")($rootScope));
};


HTML

<div class="form-group col-lg-12 col-md-12 col-sm-12 col-xs-12" id="cameraControls"></div>


Output

<vlc-controls class="ng-scope"><button class="btn btn-default btn-sm margin-r-10 text-center ng-scope"><i class="fa fa-backward"></i></button><button class="btn btn-default btn-sm margin-r-10 text-center ng-scope"><i class="fa fa-play" id="play-pause"></i></button><button class="btn btn-default btn-sm margin-r-10 text-center ng-scope"><i class="fa fa-forward"></i></button></vlc-controls>

<vlc-controls class="ng-scope"><button class="btn btn-default btn-sm margin-r-10 text-center ng-scope"><i class="fa fa-backward"></i></button><button class="btn btn-default btn-sm margin-r-10 text-center ng-scope"><i class="fa fa-play" id="play-pause"></i></button><button class="btn btn-default btn-sm margin-r-10 text-center ng-scope"><i class="fa fa-forward"></i></button></vlc-controls>


How do I remove/delete previous/duplicate element and append only the latest ?

Answer

Use .empty , you can remove all element from id cameraControls

var elmnt = angular.element( document.querySelector( '#cameraControls' ) );
elmnt .empty();
Comments