Search code examples
javascriptangularjsdomwebcam

How do I get a webcam working with AngularJS?


Previously I've put working webcam code into my application, but now it's not working when I updated to AngularJS v1.5.0. I am using webcam-directive which was working perfectly with v1.3.0.

Here is my code:

<webcam placeholder="selfiePlaceHolder"
  on-stream="onStream(stream)"
  on-access-denied="onError(err)" on-streaming="onSuccess(video)">
</webcam>

But now it's giving following error with AngularJS v1.5.0:

Uncaught Error: [$parse:isecdom] Referencing DOM nodes in Angular expressions is disallowed! Expression: onSuccess(video)
http://errors.angularjs.org/1.5.0/$parse/isecdom?p0=onSuccess(video)

I also tried to use a different solution with AngularJS ng-Camera but even its demo page is not working for me.

Note: I know the issue is that we can't access the DOM from the newer version of AngularJS, but the same code works with the older version. I need to know how to pass the "Video" DOM object to the controller.


Solution

  • I've found the solution to the problem. Two things need to be done:

    First In HTML:

    <webcam channel="channel" 
            on-streaming="onSuccess()" 
            on-error="onError(err)" 
            on-stream="onStream(stream)"></webcam>
    

    Secondly, in the controller, you can access the DOM video with the following code:

     $scope.onSuccess = function () {
            // The video element contains the captured camera data
            _video = $scope.channel.video;
            $scope.$apply(function() {
                $scope.patOpts.w = _video.width;
                $scope.patOpts.h = _video.height;
                //$scope.showDemos = true;
            });
        };
    

    Here is a working example.