我使用getUserMedia来获取音频流。音频流仅在getUserMedia的回调中可用。但是,当我尝试从回调内部更新绑定时,angular不会检测到更改并且不会更新绑定。我试图使用$ scope。$适用于许多文章的建议,但它似乎没有做任何事情。
这是一个小提琴,展示了我尝试过的东西。 http://jsfiddle.net/poptart911/a00koc8r/1/
angular.module('test', [])
.controller('mainController', function ($scope) {
this.deviceStatus = "Angular works.";
this.deviceStatus = "We can update a binding.";
navigator.mediaDevices.getUserMedia({
audio: true,
video: false
}).then(function (stream) {
this.deviceStatus = "Angular doesn't detect this change.";
$scope.$apply(function (stream) {
this.deviceStatus = "I even tried scope.apply!";
alert("But I know this code is executing");
});
});
});
答案 0 :(得分:1)
$scope.$apply
按预期工作。但是,this
的范围是指内部lambda函数的范围,而不是首先声明deviceStatus
的外部函数的范围。因此,getUserMedia
回调会创建一个 new deviceStatus
变量,而不是更改原始变量(UI绑定到该变量)。尝试存储对原始this
的引用,并在引用内部lambda函数中的deviceStatus
时使用它:
angular.module('test', [])
.controller('mainController', function ($scope) {
var that = this;
that.deviceStatus = "Angular works.";
that.deviceStatus = "We can update a binding.";
navigator.mediaDevices.getUserMedia({
audio: true,
video: false
}).then(function (stream) {
that.deviceStatus = "*Now* angular detects this change.";
$scope.$apply(function (stream) {
that.deviceStatus = "I even tried scope.apply!";
alert("But I know this code is executing");
});
});
});
Here's a working jsfiddle as a demonstration。 getUserMedia
函数已替换为setTimeout
,因为该函数似乎对我无效。