简体   繁体   中英

How can I access a scope inside a promise in Angularjs?

So this is my 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()
    }
})

And my problem is that the $scope.spinner and $scope.talkButton doesn't work as expected. I tried putting it before the promise and it works. So I tried something like

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

But still no changes and no errors. Am I doing it wrong? Any help would be much appreciated.

maybe the digest cycle might be stopped. i think using scope.apply() might fix your problem.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM