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

时间:2015-12-01 02:20:37

标签: javascript angularjs getusermedia

我使用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");
        });
    });
});

1 个答案:

答案 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 demonstrationgetUserMedia函数已替换为setTimeout,因为该函数似乎对我无效。