简体   繁体   中英

$scope.$watch only triggered once

I've set the following watcher in my controller:

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

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

This should fire when embeds changes. I have the following functions that check if all my embedded Tweets and Facebook posts have loaded for the page. When all Tweets or Facebook posts are loaded, it updates embeds within a $timeout block in order to trigger a digest cycle.

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

The problem I'm having is that my watcher only fires once when I set it. I've tried binding embeds to $scope and/or watching embeds.twitter and embeds.facebook but the watcher only ever fires once.

Use:

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

See https://docs.angularjs.org/api/ng/type/ $rootScope.Scope. First argument must be string or function which return the name of param.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM