从Angular页面中删除img-element

时间:2015-04-29 03:03:19

标签: javascript jquery angularjs element angular-directive

我正在创建一个有角度的网页应用,我首先要在其中显示图像,但是当您点击按钮时,我想删除此默认图像并将其替换为网络摄像头的视频流。但到目前为止,删除图像元素仍然很难......

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);
    }
  });
}
  };

}]);

有谁知道我做错了什么?

2 个答案:

答案 0 :(得分:3)

您不应该尝试明智地删除该DOM。而是使用有条件地在页面上呈现元素的ng-if

例如,在您的HTML中

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

然后在你的指令中:

    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
        } 

答案 1 :(得分:0)

我使用了属性wc_add_notice( __( 'Thing removed.', 'your-textdomain' ), 'error' );

setAttribute(src, "")