programing

각도 JS 및 방향 링크 및 $timeout

minimums 2023. 2. 27. 23:02
반응형

각도 JS 및 방향 링크 및 $timeout

Angular의 매우 기본적인 예에 문제가 있습니다.JS와 디렉티브.webrtc에서 웹캠 이미지를 보여주는 디렉티브를 만들고 싶습니다.내 코드는 스트림을 완벽하게 표시하지만 타임아웃을 추가하면(예를 들어 캔버스를 새로 고치는 경우) $timeout이 작동하지 않습니다.이 코드는 다음과 같습니다.

wtffDirectives.directive('scannerGun',function($timeout){
    return {
        restrict: 'E',
        template: '<div>' +
            '<video ng-hide="videoStatus"></video>' +
            '<canvas id="canvas-source"></canvas>' +               
            '</div>',
        replace: true,
        transclude: true,
        scope: false,
        link: function postLink($scope, element){
           $scope.canvasStatus = true;
           $scope.videoStatus = false;

           width = element.width = 320;
           height = element.height = 0;

           /* this method draw the webcam image into a canvas */
           var drawVideoCanvas = function(){
              sourceContext.drawImage(vid,0,0, vid.width, vid.height);
           };

           /* start the timeout that take a screenshot and draw the source canvas */
           var update = function(){
              var timeout = $timeout(function(){
                console.log("pass"); //the console log show only one "pass"
                //drawVideoCanvas();
              }, 2000);
           };

           /* this work perfectly and reproduct into the video tag the webcam */
           var onSuccess = function onSuccess(stream) {
              // Firefox supports a src object
              if (navigator.mozGetUserMedia) {
                 vid.mozSrcObject = stream;
              } else {
                 var vendorURL = window.URL || window.webkitURL;
                 vid.src = vendorURL.createObjectURL(stream);
              }
              /* Start playing the video to show the stream from the webcam*/
              vid.play();
              update();
           };

           var onFailure = function onFailure(err) {

              if (console && console.log) {
                console.log('The following error occured: ', err);
              }
              return;
           };

           var vid = element.find('video')[0];
           var sourceCanvas = element.find('canvas')[0];
           var sourceContext = sourceCanvas.getContext('2d');

           height = (vid.videoHeight / ((vid.videoWidth/width))) || 250;
           vid.setAttribute('width', width);
           vid.setAttribute('height', height);

           navigator.getMedia (
              // ask only for video
              {
                video: true,
                audio: false
              },
              onSuccess,
              onFailure
           );
         }
       }
    });

뭐가 문제죠?왜 이 상황에서 $520이 작동하지 않는가?해결책을 찾을 수 있을까요?

미리 감사드린다

다른 모듈과 마찬가지로 디렉티브에 의존관계를 주입할 수 있습니다.

.directive('myDirective', ['$timeout', function($timeout) {
   return {
        ...
        link: function($scope, element){
            //use $timeout
        }
    };
}]);

코드에서 코멘트는 '하나의 패스만 표시'라고 되어 있습니다.타임아웃은 지정된 지연 후에 1회만 실행됩니다.

아마 당신은 준비를 원할 것이다.반복 콜을 셋업하는 간격(각 1.2보다 이전인 경우)/$interval(1.2보다 새로운 경우).setInterval 버전은 다음과 같습니다.

var timeout = setInterval(function(){
    // do stuff
    $scope.$apply();
}, 2000); 

이것은 외부 jQuery 콜이기 때문에 DOM을 업데이트하기 위해 angular에 지시해야 한다는 것을 상기시키기 위해 $apply를 포함했습니다.($timeout이 각도 버전인 경우 자동으로 DOM 업데이트)

의심스러웠는지 모르겠지만$timeoutjavascript 플레인이나setTimeout기능, 그리고 그것은 오직 한 번만 실행되어야 한다.setInterval.

Angular 1.2.0을 사용하는 경우 서비스를 변경합니다. 그렇지 않으면 1.0 버전을 사용하는 경우 재귀화할 수 있습니다.

var timeout;
var update = function() {
  // clear previous interval
  timeout && timeout();
  timeout = $timeout(function() {
    // drawSomething(...);
    update();
  }, 2000);
}

언급URL : https://stackoverflow.com/questions/19472058/angular-js-and-directive-link-and-timeout

반응형