AngularJs interval displays only the variable {{name}}

I am attempting to retrieve a list of all 'cashflow' objects in my django application by utilizing an AngularJS get function that runs every 5 seconds. The function is triggered with $interval(getCashflows, 5000); in my JavaScript file, and I aim to display the results in my HTML using [[getCashflows]] (refer to interpolateProvider).

However, all I see in my HTML is "[[getCashflows]]." Is the interpolateProvider not functioning correctly, or am I missing something in the way I call it?

 app = angular.module("coco",[]);

app.config(function($interpolateProvider) {
    $interpolateProvider.startSymbol('[[');
    $interpolateProvider.endSymbol(']]');
});

app.controller('cocoCtrl',['$scope','$http', function($scope) {

    $scope.save = function (cashflow) {
        var dataObj = {
                value : cashflow.value,
                date : cashflow.date,
        };
        $.ajax({
            url : "/create_cashflow/", // view functie
            type : "POST",
            data : dataObj,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            success : function(json) {
                $(".data").prepend("<li><strong>"+json.value+"</strong> - <em> "+json.date+"</em></li>");

            }
        });
    }

}]);

app.controller('cocogetCtrl',['$scope','$http', function($scope,$http, $interval) {

    $scope.cashflows = "";
    $interval($scope.getCashflows = function() {
        return $http.get("/get_cashflows/", {data:data}).then(function(response) {
            $scope.cashflows = "test";
            alert(response.toString());
            $(".flows").prepend("<li><strong>"+json.value+"</strong> - <em> "+json.date+"</em></li>");
            return response.toString();

        });
    }, 5000);
}]);

Answer №1

The issue you are facing is most likely due to trying to update an angular scope variable from a jQuery callback. Angular only monitors changes to the scope within its own digest loops, so any updates happening outside of that context will not be recognized by Angular.

To resolve this, it is recommended to avoid using $.ajax() calls and instead utilize the $http service that is already available in your controller.

However, it may not be clear what you expect to display in your HTML. The function getCashflows does not return a value directly, especially when using $http. Since the value is fetched asynchronously from the server, you should modify it so that the scope value becomes a promise that resolves to the expected data. You can achieve this by:

function getCashflows() {
   $scope.cashFlows = $http.get("/get_cashflows/", {data:data})
   .then(function(response) {
       return response.data;
   });
}

Update your HTML to use the interpolated value cashFlows instead of the function itself.

There is no necessity for getCashflows to be exposed to the scope. It can simply be treated as a regular function, which also addresses the issue with the current call to $interval causing JavaScript to halt because of an unresolved name.

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

Navigating a sortable list using jQuery

I have integrated the "sortable" script from on my web application to create a sortable list of items. While the sorting functionality works perfectly, I now need to update my server with the new order whenever changes are made. To capture the sorting ev ...

Retrieve the Axios response without interruption, even in the event of an exception, when making API calls with multiple files

Currently, as a beginner diving into Vue.js, I am exploring the world of frontend development by integrating Vue with my Laravel backend. To streamline my API calls and make them more organized for different models, I decided to create a separate file name ...

Angular is capable of transforming the date into the format of dd/mm/yyyy

Received date format from the server is as follows: "tranDate":"2015-11-29T18:30:00.000Z" When trying to display the date in the view using the code snippet below, the date appears as - 30/11/2015 (it should be 29/11/2015). <td>{{stmt.tranDate | d ...

`Angular2 - exploring the complexities of function scope`

I'm facing a challenge while working on my Angular2 Sample with the http module. Here is a snippet from my component: app.loginComponent = ng.core.Component({ selector: 'login', templateUrl: 'app/login/login.html&ap ...

Create a visual representation of an item within a framework using an Angular directive

I am interested in using a directive to draw a triangle above a series of div elements. In my scenario, I have four squares and two values: charge and normal. The value of charge determines the color of the squares, while normal is used for drawing the t ...

I'm curious about how I can selectively utilize vuex-persistedstate with Nuxt for certain stores only

Check out this library: https://github.com/robinvdvleuten/vuex-persistedstate. I have customized the provided plugin file for Nuxt. import createPersistedState from 'vuex-persistedstate' export default ({ store }) => { createPersistedState ...

What is the best way to seek verification when relocating a node within Angular's UI Tree?

Is there a way to prompt for confirmation when moving a node in Angular UI Tree? When moving a node between trees, is there a method to display a confirmation message? I attempted to utilize the dragStop callback. <div data-ui-tree="treeOptions" id= ...

Ensuring uniqueness of group by values in JavaScript when a textbox loses focus

Make sure the first column is unique by preventing duplicate entries in the second column textbox using JavaScript on blur event. <table rules="all" class="table table-bordered"> <tbody> <tr> < ...

Explain the contrast between specifying a function name in the onclick react event versus invoking it using a callback

Can someone explain the distinction between these two React statements? <Button onClick={this.Callme}></Button> <Button onClick={()=>this.Callme()}></Button> Is it merely a syntax difference or is there an impact on functional ...

Looking to add some color to the tags within an XML document that is being shown in a textarea?

Currently, I am attempting to add color to the tags within an XML string that is being displayed in a textarea on an HTML page. For example, let's say I have an XML string stored in a variable called 'xmldata'. The HTML textarea tag looks ...

Ways to enable automatic scrolling of a page as the content expands (Utilizing collapsible elements)

For a recent project I've been working on, I decided to include 4 collapsible text boxes. However, I encountered an issue where opening content1 would expand and push down content2-4, requiring the user to manually scroll to view the remaining collaps ...

What causes a failed assertion to activate a promise catch block?

During my unit testing of an Angular application, I encountered some unexpected outcomes. After analyzing the issue, I was able to replicate the problem in a sample test case. The failure of the should.equal(true, false, 'should then') assertion ...

Exploring OOP Strategies within the Angular MVC Framework!

After coming across a question on Stack Overflow that was similar to mine, I realized I have a lot to learn about Object-Oriented Programming (OOP). Up until now, my coding experience has been mainly procedural. Before diving into my question, let me provi ...

JavaScript - Setting Image IDs upon Page Load

I've encountered a challenge with assigning IDs to elements containing the "img" tag. I've attempted to find solutions from others facing similar issues, but none of them quite align with my own problem. I am fairly new to Javascript and suspect ...

How to apply a series of spaces using span/tspan with jquery/javascript

Check out this fiddle: http://jsfiddle.net/jzLu4toe/3/ <span id='tghj'></span> $('#tghj').text('Hey There'); I'm facing an issue where I need to insert multiple spaces inside a span element. ...

Customizing label text based on radio button selection - A step-by-step guide

JavaScript Code <script> handleClick = function(val) { document.getElementById('selectnumber').innerHTML = val; }; </script> HTML Code <ul><li><fieldset class="rating"> <legen ...

How to Safely Merge Data from Several Excel Files into a Single Worksheet in Google Sheets using ExcelJS without Overwriting Existing Data

Just to clarify - I'm not a seasoned developer, I'm still a newbie at this. My current challenge involves transferring data from multiple Excel files located in one folder to a single worksheet in Google Sheets. To do this, I am utilizing excelJ ...

Repeatedly encountering identical values in delayed for loop

I can't figure out why my delayed for loop is consistently giving me a "-1" as the result. for (var i = 5; i > 0; i--) { setTimeout(function() { console.log(i) }, i * 1000) } (I adjusted my variable to be 5) ...

Tips for Incorporating the YouTube Iframe API into Your ReactJS Project

While working in React, I am attempting to build a custom YouTube player component that includes a new set of player controls. The YouTube iframe API provides the following code snippet for creating a player instance: var tag = document.createElement(&ap ...

using mongoose to fetch information and storing it in an array

I am getting an undefined return. What is the best way to store the retrieved data in an array? function storeUsers(place) { if (place === 'France') { myModel.find({}, (err, result) => { var userArray = []; ...