如何在Angularjs中访问promise中的范围?

时间:2017-06-11 12:42:55

标签: javascript angularjs

所以这是我的控制器:

translateApp.controller('translateCtrl', function ($scope, $http) {
    $scope.spinner = false;
    $scope.talkButton = true;

    function redirectRecognizedTextOutput() {
        artyom.redirectRecognizedTextOutput((recognized, isFinal) => {
            if (isFinal) {
                // scope can't be read
                $scope.talkButton = true;
                $scope.spinner = false;
            } else {
                console.log("wait")
            }

        });
    }

    $scope.start = function () {
        // I set spinner and talkButton values and call the function
        $scope.spinner = true;
        $scope.talkButton = false;
        redirectRecognizedTextOutput()
    }
})

我的问题是$scope.spinner$scope.talkButton没有按预期工作。我试着把它放在诺言之前,它有效。所以我试过像

这样的东西
function redirectRecognizedTextOutput() {
    var vm = this
    artyom.redirectRecognizedTextOutput((recognized, isFinal) => {
      if (isFinal) {
        vm.spinner = false;
        vm.talkButton = true;
      } else {
        console.log("wait")
      }
    });
 }

但仍然没有变化也没有错误。我做错了吗?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

可能会停止摘要周期。我认为使用scope.apply()可能会解决您的问题。

function redirectRecognizedTextOutput() {
    var vm = this
    artyom.redirectRecognizedTextOutput((recognized, isFinal) => {
      if (isFinal) {
        vm.spinner = false;
        vm.talkButton = true;
      } else {
        console.log("wait")
      }
      $scope.$apply()
    });
 }