How to get the current date with Angularjs with refresh on date?

Asked

Viewed 2,301 times

2

How to do a refresh only on an "ng-Binding" and not on the page, to get the current date via Angularjs?

I have the following code:

function updateTime() {
                scope.time = new Date();
            }

But I need to do a refresh, so that it is synchronized with the logic, that is: Whenever update the minute, in my html it also updates.

 <span>{{time|date: 'hh:mm a'}}</span>

I saw something about the $intervalbut so far I have not succeeded, if someone can explain how to use the same, or another way to get the same result, I am grateful.

1 answer

2


The $interval¹ implements the window.setInterval², that runs a block of code repeatedly, within a specific range. I implemented the code below taking as reference the example implemented using directives.

var app = angular.module('clock', []);

app.controller('ClockController', ['$scope', '$interval', 'dateFilter', function($scope, $interval, dateFilter) {
  $scope.currentTime = dateFilter(new Date(), 'hh:mm');
  
  var updateTime = $interval(function() {
    $scope.currentTime = dateFilter(new Date(), 'hh:mm');
  }, 1000);
}]);
<div ng-app="clock" ng-controller="ClockController">
  {{ currentTime }}
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

  • great tip, that’s exactly what I wanted. But what would be the difference of using the $timeout and the $interval you could tell me?

  • The $timeout delays the execution of the function, while the $interval runs it repeatedly. That is, the first executes the function after the specified interval, while the second executes the function at each interval.

  • thanks for the explanation. I managed to solve my problem with the $interval. A hug.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.