2014-10-20 127 views
1

我阅读了有关$ digest周期的文章和$ scope。$ apply()尽可能多,但无法理解如何在回调中更改我的数据。从未调用回调

这是我的方法:

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,真) - 做一些异步工作,vm.showAll了。 之后我想将它设置为false。

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

+0

您是否收到JavaScript错误?如果是这样,那是什么? – 2014-10-20 14:25:06

+0

'vm.search'正在执行任何_asynchronous_工作吗? – 2014-10-20 14:25:12

+0

嗨,不,我不知道。只是我从来没有在这条线:vm.showAll = false; – Artem 2014-10-20 14:25:57

回答

2

直接回答你的问题:我强烈怀疑,你得到console.error:

$apply already in progress

这将导致$适用回调无法运行。

也就是说,你可以通过使用$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递延法(还依赖注入),它返回一个承诺,并呼吁.resolve /拒绝,你用。然后使用这样的:

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;  
 
     }); 
 
    }); 
 
}