Search code examples
javascriptangularjsionic-frameworkcordova-plugins

how can i execute the( if ) statement after finishing the speak recognition


It compares the variable comp when it still empty. It should take the speech recognizer value before. How can I fix that? How can I let it wait until the speech recognizer finish its job?

.controller('LearnCtrl', function($scope , $ionicSlideBoxDelegate, Slides ) {

$scope.slides = Slides.all();

$scope.hear = function() {
    navigator.tts.startup();
    navigator.tts.setLanguage('fr');

    navigator.tts.speak($scope.slides[$ionicSlideBoxDelegate.currentIndex()].name);
 }

$scope.spell = function() {
    var maxMatches = 1;
    var promptString = "Speak now";
    var language ='fr-FR'
    var comp ="";

    window.plugins.speechrecognizer.startRecognize(function(result) {
        comp=result ; 
    }, function(error) {
        alert("connexion lost"+error);
    }, maxMatches, promptString, language);


    if (comp==$scope.slides[$ionicSlideBoxDelegate.currentIndex()].name){
        alert('good job')
    } else {
        alert('try again');
    }

}

Solution

  • It's quite possibly async, so try putting the comparison inside the function you pass into startRecognize.

    window.plugins.speechrecognizer.startRecognize(function(result) {
        comp=result;
        if (comp==$scope.slides[$ionicSlideBoxDelegate.currentIndex()].name){
          alert('good job')
        } else {
          alert('try again');
        }
    }, function(error) {
        alert("connexion lost"+error);
    }, maxMatches, promptString, language);