Having trouble with window.setInterval in AngularJS?

My coding snippet involves the use of the setInterval method:

function MyController($scope) {
    $scope.clock = new Date();
    var updateClock = function() {
        $scope.clock = new Date();
    };
    setInterval(updateClock, 1000);
};

The HTML associated with this is as follows:

<!doctype html>
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js"></script>
</head>
<body>
    <div ng-controller="MyController">
        <h1>Hello {{ clock }}!</h1>
    </div>
    <script type="text/javascript" src="script.js"></script>
</body>
</html>

However, there seems to be an issue with the update functionality in setInterval inside MyController. What could possibly be wrong here?

As per a reference source, it should be done like this:

function MyController($scope) {
    $scope.clock = new Date();
    var updateClock = function() {
        $scope.clock = new Date();
    };
    setInterval(function() {
        $scope.$apply(updateClock);
    }, 1000);
    updateClock();
};

Why does using $scope.$apply make a difference and what might go awry if it's not included?

Answer №1

Implement the use of the built-in $interval service provided by Angular.

angular.module('myApp', []).controller('ClockController', function($scope, $interval) {
    $scope.clock = new Date();
    var updateClock = function() {
        $scope.clock = new Date();
    };
    $interval(updateClock, 1000);
});

Answer №2

When utilizing the JavaScript function setInterval(), remember to include $scope.$apply() in your method.

var updateClock = function() {
        $scope.clock = new Date();
        $scope.$apply();
    };

An alternative and more efficient approach is to utilize $interval (angular)

$interval(updateClock, 1000);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using setInterval in JavaScript to automatically update a TextField

As someone who is relatively new to Javascript and jQuery, I am trying to make a simple code that updates a text field with random values every 5 seconds. However, my implementation does not seem to be working. I apologize if this question seems too basic ...

Identifying a flaw in an HTML5 video

I am attempting to identify when an error occurs while playing an HTML5 video. Specifically, I am encountering a situation where I am trying to play an HLS video on a MAC (where "canPlayType" is at least "maybe"), but the video will not play for unknown r ...

Convergence phenomenon in SVG when two distinct paths intersect

Working with individual SVG paths and in need of a mitre effect when there is a path join, which is a new concept for me. The SVG shape resembles a polygon, with each side as its own individual path. Although the sample SVG code provided does not display ...

Show alerts that automatically disappear after a set amount of time

I have successfully implemented code that displays alerts for a specific period of time, indicated by (alert alert-warning). Additionally, I want to display another type of alert, (alert alert-success), for a certain amount of time, after which the page sh ...

Inject $scope into ng-click to access its properties and methods efficiently

While I know this question has been asked before, my situation is a bit unique. <div ng-repeat="hello in hello track by $index"> <div ng-click="data($index)"> {{data}} </div> </div> $scope.data = function($index) { $scope.sweet ...

Remove the ID, class, and other attributes from an HTML string using JavaScript for sanitization purposes

Can someone help me with sanitizing HTML text provided by a user? The HTML code in question is as follows: var htmlStr = `<p id="test" class="mydemo">TEhis is test</p> <pre class="css"> &lt;html> &lt;body cl ...

Ways to update a component when the state changes

When attempting to access components that require authentication, I want to redirect to the login page if the user is not logged in. However, I am facing an issue with initializing the firebase auth object, as there is a small delay. The documentation sugg ...

Effortless method for distributing NPM-loaded modules among various Browserify or Webpack bundles

Feeling frustrated trying to find a straightforward way to share code, required via NPM, across multiple Browserify or Webpack bundles. Is there a concept of a file "bridge" that can help? I'm not concerned about compile time (I know about watchify), ...

Utilizing a JSON file for long-term storage of a compact database in JavaScript

As a newcomer to JSON, I wanted my webpage to display a small database of records in a table without using a traditional database like MySQL. Instead, I decided to read data from and write it out to a JSON file for convenient and persistent storage on my w ...

Unable to trigger onSelect event on the datepicker component

Whenever a date is chosen, I need to trigger a javascript function. Here is the javascript code: $(document).ready(function(){ var date_input=$('input[name="date"]'); //our date input has the name "date" var container=$('.bootstrap- ...

Retrieving modified object values in Node.js - A comprehensive guide

How can I retrieve the modified value of an object? The file index.js is executed before index2.js and here's what my code looks like: var object = { size:'5' }; var setSize = function(size) { object.size = size; } exports.object ...

Leveraging JQuery for form submission

My webpage contains a form with the following structure: <form action="/" method="post"> <select id="SelectedMonth" name="SelectedMonth"> <option>7/1/2017</option> <option>6/1/2017</option> </select> </form> ...

Loop through a set of data with a filter that applies to two specific

I'm trying to figure out how to use a single ng-repeat that filters based on either 'the order' or 'the id'. Here is an example of what I'm attempting: ng-repeat "cd in cds | filter: !order ? orderBy:'id' : orderBy ...

Exploring Ways to Loop through a JavaScript Map in Angular with ng-repeat

As I work on developing my Angular application, I encounter a situation where I have a Map object with keys and values (as demonstrated below). These key-value pairs in the map object (headerObj) are provided by the user as input to the application. var ...

Configuring the array interval in an Angular application

I'm facing an issue while attempting to use the setInterval() function to update text for the user every 3 seconds. My attempt at looping with a for loop has not been successful - I only see 'test 03' and nothing else. I'm struggling ...

When I navigate to the URL using a router-link, the v-for in my Vue.js component renders properly. However, if I manually type the URL or refresh the page, the v-for fails to render

Whenever I navigate to a specific URL that showcases icons of characters from a game, everything functions as expected and the icons are displayed. However, upon refreshing the page, the icons vanish. If I manually enter www.example.com/champions, the ico ...

JavaScript: Modify the dropdown class with a toggle option

Hi there, I'm currently facing a small issue and I could really use some assistance. I have a dropdown menu with two selection options - "green" and "blue", and I need to toggle a class based on the selected option. If you'd like to take a look, ...

Are there any public APIs available for testing JSONP AJAX calls?

Does anyone know of any public web API, aside from Twitter, that I can experiment with by making an ajax call using the jsonp protocol? ...

Issue arising during reconnection following a disconnection in the node-redis client

I'm struggling to understand why the SocketClosedUnexpectedlyError error is being triggered in the code snippet below: const redisClient = require('redis').createClient(); redisClient.connect().then(function() { return redisClient.disconn ...