永远不会调用回调

时间:2014-10-20 14:22:56

标签: javascript angularjs

我尽可能多地阅读有关$ digest循环和 $ scope。$ apply()的文章,但无法解决如何在回调中更改数据的问题。< / p>

这是我的方法:

vm.showAllResults = showAllResults;

function showAllResults(){
            // Prevent 'bubbling'
            event.preventDefault();
            event.stopPropagation();
            // Second parameter notifies search to show full list of elements
            vm.search(vm.input.query, true);
            $scope.$apply(function(){
                vm.showAll = false;
            });
        }

vm.search(vm.input.query,true) - 正在使用 vm.showAll 进行一些异步之后我想将其设置为false。

但我无法进入$ scope。$ apply()。我究竟做错了什么?谢谢!

1 个答案:

答案 0 :(得分:2)

直接回答你的问题:我非常怀疑你正在获取console.error:

  

$申请已在进行中

导致$ apply回调无法运行。

也就是说,您可以使用$timeout( cb )代替$ scope来解决这个问题。$ apply(cb)。如果你想使用它,请确保依赖注入它:

vm.showAllResults = showAllResults;

function showAllResults(){
  // Prevent 'bubbling'
  event.preventDefault();
  event.stopPropagation();
  // Second parameter notifies search to show full list of elements
  vm.search(vm.input.query, true);
  $timeout(function(){
    vm.showAll = false;
  });
}

然而,正如Avraam指出的那样,在我看来,vm.search应该是一个使用$q(也是依赖注入)的延迟方法,它返回一个promise,并调用.resolve / reject,你使用它与.then像这样:

vm.showAllResults = showAllResults;

function showAllResults(){
  // Prevent 'bubbling'
  event.preventDefault();
  event.stopPropagation();
  // Second parameter notifies search to show full list of elements
  vm.search(vm.input.query, true)
    .then( function() {
      $timeout( function() { // <-- This $timeout probably not needed...
        vm.showAll = false;      
      });
    });
}

相关问题