javascript - 如何访问 Angularjs 中 Promise 内的范围?

标签 javascript angularjs

这是我的 Controller :

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 无法按预期工作。我试着把它放在 promise 之前,它起作用了。所以我尝试了类似的事情

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

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

最佳答案

也许消化周期可能会停止。我认为使用 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()
    });
 }

关于javascript - 如何访问 Angularjs 中 Promise 内的范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44484003/

相关文章:

javascript - AngularJs $http 不适用于跨域

javascript - 遍历对象或数组以确定元素是否在范围内

javascript - Greasemonkey 脚本,用于将具有特定域的页面上的所有 URL 替换为不同的域

javascript - 使用删除运算符删除空函数中的 .length

javascript - 使用内容创建 Kotlin/JS WebComponent

javascript - 在第一次页面加载时设置 cookie

javascript - 如何获取最接近html元素标签的文本

angularjs - 如何单独更改相同元素的颜色?

javascript - Angularjs dom加载准备就绪

javascript - 控制字符(\n、\t 等)不会立即在文本区域输入中更新