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

Storing the radio button's selected value in local storage using Vue JS

I have a pair of radio buttons that are linked together to accept a boolean value, either true or false. I am trying to implement a functionality where the selected value is stored in local storage. For example, if true is chosen, then true will be saved i ...

Javascript - Issue: Route.post() is in need of a callback function, however it received an [object Promise] instead

I'm encountering an issue with one of my express routes. The error message I am receiving is as follows: Error: Route.post() requires a callback function but got a [object Promise] This error seems to be related to the last line in controllerFunction ...

retrieve a reply from a PHP script and incorporate it into JavaScript following an AJAX request

I've been working with an ajax call and everything seems to be running smoothly thanks to this script: $(document).ready(function() { $('.sortable').sortable({ stop: function(event, ui) { $(ui.item).effect("highlight"); ...

When attempting to display a sub view in Express, a 404 error is encountered

I am currently working with express and jade to display a web page. My intention is to render the page using this format 'http://127.0.0.1:5000/services/landfreight' but I keep encountering a 404 error. router.get('/service/landfreight' ...

JavaScript Object-Oriented Programming - Accessor method that retrieves a property from the parent

Having trouble with implementing getters and setters for model objects in Angular. Facing an error: TypeError: Cannot read property 'firstName' of undefined at User.firstName (http://run.plnkr.co/AvdF2lngjKB76oUe/app.js:35:32) The code snippet: ...

Discover the steps to linking a dropdown menu to a text input using HTML and JavaScript

I'm currently using Sublime and trying to link a dropdown menu with an input text using html, css, and javascript. When the user selects an option from the dropdown menu, I want the corresponding value to appear in the text input field. For example, i ...

Storing HTML values in a Meteor database is a common practice for web

Within my meteor project, I have a paragraph in HTML containing a JSON value as follows: {"Active Template Id":"6467","Shirt Brand":"levis","ProductId":"EB301","Brand":"on","Material":"cotton","Price":"1800","Combo Id":"S90"} I am looking to store this v ...

Is it compatible to use AngularJS with Visual Studio 2010?

I'm feeling uncertain about the performance of web applications using VS.Net 2010 and AngularJS due to the lack of posts or ideas from others. I would greatly appreciate it if someone could share their experiences. ...

Is it possible to save or write a text file in the VueJs renderer process without the need to open the dialog box?

Currently, I am working on a project using VueJs + electron, where I need to save a text file to the user's PC without any prompt or dialog box popping up. I am aware of how to do this using require('fs'), but unfortunately fs does not work ...

Enhance your website with a dynamic jQuery gallery featuring stunning zoom-in

I am currently working on a mobile website project and I'm in need of a gallery feature that allows users to zoom in on images and swipe through them using touch gestures. After some research, I haven't been able to find a suitable solution in j ...

Implement real-time data updates on charts using AngularJS

My webapp includes charts, implemented using angular-charts. The html file for the charts contains: <canvas id="pie" class="chart chart-pie" chart-data="data" chart-labels="labels"> </canvas> The controller file for this setup looks like this ...

Is it possible to delete an element from a JSON file by solely utilizing the element's ID?

I'm fairly new to JavaScript and I've tried various online solutions without success. Currently, I'm working on creating a backend for a todo list application where I aim to implement the feature to delete items from the list. Below is the ...

What is the best way to create a new browser window for a pop-up?

Using the following JavaScript code will open a popup: window.open('http://www.google.com','mywindow','width=400,height=200'); If you call it two times like this: window.open('http://www.google.com','mywindow ...

How can I retrieve a variable in a JavaScript AJAX POST request?

Similar Question: How to retrieve a variable set during an Ajax request I am facing a challenge, as I am making an ajax call and receiving a number as the response. My query is, how can I assign this returned number to a variable that is accessible ou ...

Encountering difficulties accessing the array in the controller through ajax

Having trouble receiving an array of data from AJAX to the controller. $.ajax({ type: "POST", url: "/Home/List", traditional: true, contentType: 'application/json', data: { "Query&quo ...

What is the method for locating an element within an array?

The content being returned is presenting a challenge. How can I retrieve data from inside 0? I attempted to access it using date[0] without success const { data } = getData(); The result of console.log(data) is shown below: enter image description here ...

The networking feature stops functioning on Android devices after upgrading from Ionic 1.5.0 to 1.6.3

After upgrading from ionic 1.5.0 to 1.6.3 (the latest version), I noticed that networking ajax calls were no longer working on Android. I had to remove and re-add the android platform, and there seemed to be a change in the apk names from MainActivity-debu ...

How can I make Material UI's grid spacing function properly in React?

I've been utilizing Material UI's Grid for my layout design. While the columns and rows are functioning properly, I've encountered an issue with the spacing attribute not working as expected. To import Grid, I have used the following code: ...

By utilizing the power of JSONP, data transfer limitations can be eliminated

Is it possible to remove the limitation on data sent using JSONP? Here's my code. I'm attempting to send 3000 characters (an image converted to base64 data) at a time to a service (serviceCall.ashx). Since my data is quite large, up to 30,000-40, ...

Troubleshooting Date Errors in Typescript with VueJS

Encountering a peculiar issue with Typescript while attempting to instantiate a new Date object. <template> <div> Testing Date</div> </template> <script lang="ts"> import Vue from "vue"; export default Vue.extend({ name: ...