質問

I have an angularjs app with two controllers and they will be using the same factory of getting the time. This is mainly so that when you switch controllers the clock will persist. I have made several different attempts and implimentations of the factory and how its getting called by the controller, but none have worked so far.

Would some one mind looking at my code and telling whats missing?

app.controller('SettingsCtrl', function($scope, DateService) {
    $scope.date = DateService.updateTime;

    DateService.tick();
});


app.factory('DateService', function($timeout) {
    var service = {
        updateTime: {},
        tick: function() {
            service.updateTime = new Date();
            // runs update function every second
            $timeout(service.tick, 1000);
        }
    };
    return service;

});

I know I will need to kick off the timeout() in the controllers, which I am trying to achieve with DateService.tick()

役に立ちましたか?

解決

if you want, that $scope.date have the actual tick time you need to watch the uptime - like so:

$scope.$watch(
   function() { return DateService.updateTime; }, 
   function(newValue){ $scope.date = newValue;}
);

here is a plunkr: http://plnkr.co/edit/2obW7z?p=preview

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top