Search code examples
javascriptjqueryangularjselementangular-directive

Remove img-element from Angular page


I'm creating an angular web app in which I want to show an image at first, but when you click on a button, I want to remove this default image and replace it with a videostream of the webcam. But so far, removing the image - element remains hard...

angular.module('qrWebapp').directive('qrScanner', ['$timeout', 'openScannerService', function($timeout, openScannerService) {
  return {
    restrict: 'E',
    scope: {
      ngSuccess: '&ngSuccess',
      ngError: '&ngError',
      ngVideoError: '&ngVideoError'
    },
    link: function(scope, element, attrs) {
      var isOpen;
      var onlyOpenOnce = 0;

      var image = document.createElement('img');
      image.setAttribute('id', 'defaultImage');
      image.setAttribute('src', 'assets/images/defaultimage.png');
      image.setAttribute('width', '400');
      image.setAttribute('height', '300');
      image.setAttribute('alt', 'defaultimage');

      scope.$on('handlePublish', function() {
        isOpen = openScannerService.sharedBoolean;

        if(isOpen){
        //some code
           //finding the image on the angular page    
           var findedElement = angular.element('#defaultImage');
           findedElement.remove();

           var context;

           if(onlyOpenOnce < 1){
             angular.element(element).append(video);
             angular.element(element).append(canvas);
             context = canvas.getContext('2d'); 
           }

           onlyOpenOnce++;
    } 
    else {

      angular.element(element).append(image);
    }
  });
}
  };

}]);

Does anyone have any idea what I'm doing wrong?


Solution

  • You should not try to remove that DOM wise. Instead use ng-if that conditionally renders elements on your page.

    For e.g., in your HTML

        <img id="imgID" src="assets/images/defaultimage.png" ng-if="renderImage" />
        <canvas ng-if="renderCanvas"></canvas>
    

    and then in your directive:

        link: function(scope, element, attrs) {
            scope.renderImage = false; // Renders image by default
            scope.renderCanvas = true; // Renders Canvas by default
    
            scope.$on('handlePublish', function() {
                scope.renderImage = false; // The image element will be removed from the DOM
                scope.renderCanvas = true; // The canvas element will be rendered in the DOM
            }