2015-07-21 51 views
1

我有以下之後$手錶回調執行:

$scope.$watch('duration.dayPreference',function(value){ 
     console.log(value); 
     if(value=='every') 
     { 
      that.duration.days = 1; 
     } 
     else if(value=='selected') 
     { 
      //alert('test'); 
      that.duration.days=[]; 
     } 
     else if(value=='everyday') 
     { 
      that.duration.days='everyday'; 
     } 

    }); 

    this.selectDay = function (day) { 
     $scope.duration.dayPreference = 'selected'; 
     //$scope.$apply(); 
     /*if(typeof(this.duration.days)!='object') 
     { 
      this.duration.days=[]; 
     }*/ 

     var index = this.duration.days.indexOf(day); 
     if (index == -1) { 
      //alert('test2'); 
      this.duration.days.push(day); 
     } 
     else { 
      this.duration.days.splice(index, 1); 
     } 
    } 

在此,當我做$scope.duration.dayPreference = 'selected';我預計線下之有this.duration.days設置爲空陣列。但事實並非如此。經仔細檢查,我發現$ watch中的回調在分配下方的行之後運行。

$ watch可能很有可能在內部使用某些定時器。那麼應該怎麼做呢。

回答

1

在摘要運行之前手錶不會被觸發。這將會在你的整個功能競爭之後。

如果您認爲AngularJS本身是用JavaScript編寫的,那麼當時它就沒有辦法對您設置屬性做出反應。你正在使用線程。它只能等你完成然後作出反應。

至於怎麼做,而不是...
也許你可以手動調用該手錶功能?
或者,也許期望空數組的代碼應該屬於手錶內?

0

手錶將在$digest上觸發,這將在當前循環/代碼運行完成後觸發。你需要找出重新安排你的代碼異步處理事物的方法。一個可能的快速的解決方案可能是:

var selectedDays = []; 
$scope.$watch('duration.dayPreference',function(value){ 
    console.log(value); 
    if(value=='every') 
    { 
     that.duration.days = 1; 
    } 
    else if(value=='selected') 
    { 
     //alert('test'); 
     that.duration.days = selectedDays; 
    } 
    else if(value=='everyday') 
    { 
     that.duration.days='everyday'; 
    } 

}); 

this.selectDay = function (day) { 
    $scope.duration.dayPreference = 'selected'; 

    var index = selectedDays.indexOf(day); 
    if (index == -1) { 
     //alert('test2'); 
     selectedDays.push(day); 
    } 
    else { 
     selectedDays.splice(index, 1); 
    } 
} 
+0

(請注意,'that.duration.days'陣列,'selectedDays'創建一次,而不是重新創建每次'dayPreference'變化相反,舊陣時「記住了。 「,並且將包含您放入其中的任何內容。) – DRobinson