0

I'd like to update the html values, any second, from the controller (or service) but I didn't understand why the $watch doesn't work as aspected. Why when the update fn is called $watch doesn't see the changes?

html:

<body ng-app="app">
<div ng-controller="BitWatch as bw">

    <p>{{bw.watch.hours}}</p>
    <p>{{bw.watch.mins}}</p>
    <p>{{bw.watch.secs}}</p>

</div>
</body>

js:

angular.module("app", [])
       .controller("BitWatch", ["$scope", BitWatch])
       .service("bitTime", bitTime);


function BitWatch($scope){
    var self = this;
    self.watch = new bitTime();
    $scope.secs = self.watch.secs;
    setInterval(function(){ self.watch.update(); $scope.secs = self.watch.secs; console.log(self.watch.secs, $scope.secs);}, 3000);
    $scope.$watch( "secs", function(){ self.watch.update(); $scope.secs = self.watch.secs; console.log("chaged", self.watch.secs, $scope.secs); } );

}


function bitTime(){
    var date = new Date();
    var self = this;

    var hours = date.getHours().toString(2);
    self.hours = hours.length<4 ? "0000".substr(hours.length)+hours : hours;

    var mins = date.getMinutes().toString(2);
    self.mins = mins.length<6 ? "000000".substr(mins.length)+mins : mins;

    var secs = date.getSeconds().toString(2);
    self.secs = secs.length<6 ? "000000".substr(secs.length)+secs : secs;

    self.update = function(){
        var date_updated = new Date();

        hours = date_updated.getHours().toString(2);
        self.hours = hours.length<4 ? "0000".substr(hours.length)+hours : hours;

        var mins = date_updated.getMinutes().toString(2);
        self.mins = mins.length<6 ? "000000".substr(mins.length)+mins : mins;

        var secs = date_updated.getSeconds().toString(2);
        self.secs = secs.length<6 ? "000000".substr(secs.length)+secs : secs;
    }

}

1 Answer 1

1

Because the changes to the scope aren't applied when you use setInterval. Use $interval instead. https://docs.angularjs.org/api/ng/service/$interval

Sign up to request clarification or add additional context in comments.

1 Comment

Can you help me to undertand how to use it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.