如何使用 getUserMedia 流中的数据更新 angular 绑定?

How can I update angular bindings with data from a getUserMedia stream?

我正在使用 getUserMedia 获取音频流。音频流仅在 getUserMedia 的回调中可用。但是,当我尝试从回调内部更新绑定时,angular 不会检测到更改并且不会更新绑定。我试过按照许多文章的建议使用 $scope.$apply ,但它似乎没有做任何事情。

这里有一个 fiddle 展示了我的尝试。 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");
        });
    });
});

$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 demonstrationgetUserMedia 函数已替换为 setTimeout,因为该函数似乎对我不起作用。