AngularJS中的回调函数

时间:2015-10-22 15:17:10

标签: angularjs

我试图在回调函数中为变量赋值。多少我知道回调函数是异步的,所以我试着用scope.apply但它似乎没有工作.. 有任何想法吗 ?

angular.module("sadf")

    .factory("browsersCameraSupportService", function ($scope, $apply ) {

        return {

            supportsGetUserMedia: function () {

                navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
                var hasCam = true;
                if (navigator.getUserMedia) {
                    navigator.getUserMedia({video: true}, function(localMediaStream){

                    }, function(){

                        $scope.$apply(function(){
                            hasCam = false;
                        });
                    });
                }
                return angular.isDefined(navigator.getUserMedia)&& hasCam;
            }
        };
    });

1 个答案:

答案 0 :(得分:1)

使用$ apply的情况并非如此。由于检查媒体是异步操作,因此返回promise对象并在使用代码时使用它是很方便的。那么您的服务将成为:

angular.module("sadf")

.factory("browsersCameraSupportService", function($q) {

    return {

        supportsGetUserMedia: function() {

            navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

            return $q(function(resolve, reject) {
                if (navigator.getUserMedia) {
                    navigator.getUserMedia({video: true}, function(localMediaStream) {
                        return resolve(true);
                    }, function() {
                        return resolve(false);
                    });
                }
            });
        }
    };
});

用法很简单:

browsersCameraSupportService.supportsGetUserMedia().then(function(supported) {
    if (!supported) {
        alert('Video is not supported.');
    }
});

演示: http://plnkr.co/edit/BTj6deHrIvKa2VK3Kn1M?p=preview