我试图在回调函数中为变量赋值。多少我知道回调函数是异步的,所以我试着用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;
}
};
});
答案 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.');
}
});