2014-10-20 50 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;  
 
     }); 
 
    }); 
 
}