2016-03-05 98 views
1

我設置在我的控制器以下守望者:

var embeds = {twitter: false, facebook: false}; 

$scope.$watch(embeds, function(newVal, oldVal) { 
    if(embeds.twitter && embeds.facebook) $scope.loading = appLoader.off(); 
}); 

這應該火的時候,embeds變化。我有以下功能,檢查我的所有嵌入式Tweets和Facebook帖子是否已加載頁面。當所有Tweets或Facebook帖子都被加載後,它會在$timeout塊內更新embeds以觸發摘要循環。

checkFBInit(); 

twttr.ready(function(twttr) { 
    twttr.events.bind('loaded', function(event) { 
     $timeout(function() { 
      embeds.twitter = true; 
     }); 
    }); 
}); 

function checkFBInit() { 
    // Ensure FB.init has been called before attempting to subscribe to event 
    var fbTrys = 0; 
    function init() { 
     fbTrys++; 
     if (fbTrys >= 60) { 
      return; 
     } else if (typeof(FB) !== 'undefined') { 
      fbTrys = 60; 
      FB.Event.subscribe('xfbml.render', function() { 
       $timeout(function() { 
        embeds.facebook = true; 
       }); 
      }); 
      return; 
     } else { 
      init(); 
     }; 
    }; 
    init(); 
}; 

我遇到的問題是,當我設置我的守望者只能觸發一次。我已經嘗試綁定embeds$scope和/或觀看embeds.twitterembeds.facebook,但是觀察者只能發射一次。

回答

3

用途:

$scope.embeds = {twitter: false, facebook: false}; 
$scope.$watch('embeds', function(newVal, oldVal) { 
    if ($scope.embeds.twitter && $scope.embeds.facebook) { 
     $scope.loading = appLoader.off(); 
    } 
}, true); 

https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope。第一個參數必須是stringfunction,它返回參數的名稱。

+2

Upvoted你的答案,因爲它是我需要的解決方案的一半。我在第二次重新閱讀文檔後意識到,我還需要通過將'true'作爲第三個參數傳遞給觀察者來檢查對象是否相等。將觀察變量作爲字符串傳遞給觀察者是另一半問題。如果您接受編輯,我會將其標記爲答案。 – ACIDSTEALTH

+0

感謝您的評論。我曾在一年前使用角度,忘記這個細微差別:) –