AngularJS ngcontroller to be reloading data periodically

后端 未结 8 1744
自闭症患者
自闭症患者 2020-12-14 02:17

I have this working implementation af a angularJS app which fetches some links from an URL and paint them. However the links on the URL are being updated constantly, I woul

8条回答
  •  有刺的猬
    2020-12-14 02:49

    This answer builds off of drew.walker's answer, but makes it so that changing controllers will not spawn multiple endlessly running refreshes. It also runs getData immediately, instead of delaying it 1 second.

    It depends on you using Angular routes and setting Ctrls in them. If you don't, you'll need another way to determine if this controller is in scope.

    app.controller('MainCtrl', function($scope, $rootScope, $route, $timeout) {
    
        // Function to get the data
        $scope.getData = function() {
            ...
        };
    
        // Get the data immediately, interval function will run 1 second later
        $scope.getData();
    
        // Function to replicate setInterval using $timeout service.
        $scope.intervalFunction = function() {
            var currentCtrl = $route.current.$$route.controller;
            var currentlyRunning = $rootScope.myAppMainCtrlRefreshRunning;
            //do not run if the MainCtrl is not in scope
            //do not run if we've already got another timeout underway (in case someone jumps back and forth between
            //controllers without waiting 1 second between)
            if (currentCtrl === "MainCtrl" && !currentlyRunning) {
                $timeout(function() {
                    $rootScope.myAppMainCtrlRefreshRunning = true;
                    $scope.getData();
                    $scope.intervalFunction();
                    $rootScope.myAppMainCtrlRefreshRunning = false;
                }, 1000);
            };
        };
        // Kick off the interval
        $scope.intervalFunction();
    
    });
    

提交回复
热议问题