Unable to refresh the view from the controller once the promise has been resolved

On my webpage, I want to display a dynamic list of items that updates whenever the page is refreshed. To achieve this, I am using Parse to store and retrieve my items using promises. Here's a simplified example of how it works:

When the index.html page loads, HomeCtrl.js will call ItemService.getItems() to fetch the items from Parse API, then attach them to $scope.items for display on the view.

app.js

var myApp = angular.module('myApp',[]);
// Parse API keys
Parse.initialize('MCNXFhdenmpSRN1DU8EJrG3YROXaX4bg0Q5IYwKp', 'XZfWd7J9xGSZQOizu0BoAtIUYtECdci4o6yR76YN');

ItemService.js

var myApp = angular.module('myApp');
myApp.service('ItemService', function(){

// gets all Items
this.getItems = function() {
    var Item = Parse.Object.extend("Item");
    var query = new Parse.Query(Item);

    return query.find().then(function(items){
      return items;
    });
    return this;
  }

});

HomeCtrl.js

var myApp = angular.module('myApp');
myApp.controller('HomeCtrl',[ 'ItemService', '$scope',function(ItemService, $scope){

    $scope.items = [];

    ItemService.getItems()
        .then(function(results){
            $scope.$apply(function() {
                $scope.items = results;
                console.log($scope.items);
            });
        });

    console.log($scope.items);
}]);

EDIT

After reviewing the answers provided by others, I noticed an issue in my ng-repeat syntax. Even though the items were getting updated, they weren't reflecting on the view. I tried resolving this by updating the code as shown below:

index.html

<div ng-controller = "HomeCtrl as ctrl">
    <div ng-repeat="item in ctrl.items">
        {{item.id}}
    </div>
</div>  

HomeCtrl.js

var myApp = angular.module('myApp');
myApp.controller('HomeCtrl',[ 'ItemService', '$scope',function(ItemService, $scope){

    this.items = [];

    ItemService.getItems()
        .then(function(results){
            $scope.$apply(function() {
                this.items = results;
                console.log(this.items);
            });
        });
}]);

Answer №1

The error message you're encountering is a result of 'this' pointing to the window object when your code reaches the then function.

ItemService.getItems()
    .then(function(results){
        //At this point, 'this' refers to the window object 
       //window.items is not defined
    });

This is why the error occurs.

To resolve this issue, there are various approaches you can take, one of which involves using another object as a reference for 'this'.

var myApp = angular.module('myApp');

myApp.controller('HomeCtrl',[ 'ItemService', '$scope',function(ItemService, $scope){

var that = this;
that.items = [];

ItemService.getItems()
    .then(function(results){
            that.items = results;
    });
}]);

Give this a try and see if it resolves the problem.

Answer №2

One way to reference it in HTML is by using the following syntax:

<div ng-repeat="item in items">

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

Injecting services into AngularJS controllers helps to provide the necessary dependencies

Greetings! Here is the code snippet for my service: angular.module('lucho1App').factory('ApiExample', ['$http', '$q', function($http, $q) { return { promiseToHaveData: function() { return $ht ...

My Node JS program becomes unresponsive when reaching the resolve() method

I encountered a problem with my Node.js application when trying to list AWS Cognito users. The issue arises only when the number of Cognito users exceeds 60. API Reference Below is the snippet of my code. function checkUserPermissions(cognitoidentityse ...

Beginning a counter: a step-by-step guide

I am currently utilizing Angular to create a functional counter like so: <button ng-click="order.startOperation(operation)"> <p ng-if="counter.start"></p> </button> When the button is clicked, it triggers a function that initia ...

Can JavaScript be used to determine if any code has been executed from the browser's console?

I'm currently developing a JavaScript game and I want to prevent cheating. Is there a way for me to track and record commands entered in the JavaScript console? Here's a basic outline of what I have in mind: consoleCommands = ""; window.console ...

Strategies for testing a split get() function using expressJS and jestJS to streamline unit testing

How can I define a get() route in an Express.js application for easy unit testing? To start, I extracted the get() function into its own file: index.js const express = require('express') const socketIo = require('socket.io') const Gp ...

The Vuetify accordion template is not appearing due to a v-for loop issue in Nuxt.js

My goal is to set up an FAQ page using Nuxt.js. The template I obtained from Vuetify doesn't display correctly on my localhost. Instead, I'm encountering errors. If I replace 'v-for "(item,i) in 5" : key="i"' as per the template source ...

Tips for converting a complex MVC ViewModel with multiple List properties into a JSON format suitable for transmitting to AngularJS

Here is the MVC View model that I'm working with: public class UserViewModel { public string FirstName { get; set; } public string LastName { get; set; } public int UserID { get; set; } public IEnumerable<Role> LstRole { get; se ...

Implement AngularJS form validation to automatically trigger on model changes from various control events

I have developed a custom date range validation directive. In this directive, if the Start Date is greater than the End Date, a validation error should be thrown. The validation works correctly when I manually update the value in the Start Date textbox. H ...

File writing issues are plaguing NodeJS, with middleware failing to function as well

I am facing a challenge with my middleware that is supposed to write JSON data to a file once the user is logged in. However, I am encountering an issue where no data is being written to the file or displayed on the console when the function is executed. ...

The functionality of HTML5 Camera is experiencing issues while being used with Tomcat7

My Angular2 project includes HTML5 camera access functionality. I launch the project using Angular CLI (ng serve), which starts the web container for testing purposes. When trying to access the camera, the browser prompts me for permission. Once granted, e ...

Guide on developing a personalized validation system with Vuetify regulations for verifying the presence of an item

I'm currently working on my first CRUD web app using Vue 2 + Vuetify, but I've hit a roadblock while trying to add validation to a form. Specifically, I need to ensure that no item with the same title already exists in the database. You can view ...

Can one jQuery script be used for multiple ajax 'like' buttons?

Hey there! I'm working on an Ajax 'like' button that utilizes jQuery. This button will be utilized multiple times on a single page. I'm looking for a way to streamline the process and avoid including the jQuery script multiple times. Is ...

Using the $inc operator in mongoose to avoid decrementing a value below zero

My code successfully deducts credit from a user using $inc in Mongoose, but the concern is that the value can become negative, which is not ideal. Is there any way to prevent this? module.exports.deduct_credit = function(subscriber_email,callback){ Us ...

Identifying Changes with jQuery Event Listeners

I am trying to run some javascript code that is in the "onchange" attribute of an HTML element. For example: <input id="el" type="text" onchange="alert('test');" value="" /> Instead of using the onchange attribute, I want to trigger the e ...

Are there any publicly accessible APIs available to retrieve data values based on the file type?

Currently, I am working on a project that requires uploading and downloading files. The current functionality allows only .csv and .txt file types to be downloaded using the code snippet below: downloadFile(file).then( function (response) { va ...

Sending HTML parameters to a PHP file

I have been trying to pass the parameters from the current HTML page to a PHP page using a form. In my header in the HTML, I currently have the following function: <script> function getURLParameter(name) { return decodeURIComponent((new Re ...

Tips on stopping the page from scrolling following an ajax request (return false not effective or potentially misplaced)

I am working on a project that involves displaying a tree with information from the Catalogue of Life, including details such as Kingdom, phylum, order, and more. My approach includes using ajax/php to interact with a mySQL database and javascript to handl ...

What steps do I need to take in order to create a histogram with perfect symmetry?

I am looking to create a unique JavaScript program that can generate a symmetric histogram resembling the image provided below: This program will prompt the user to input the number of bars they want to display and specify the character used to draw the b ...

Navigating with UI-Router within a single view for both viewing and editing purposes

I have been encountering an issue with changing states between the view page and edit page using UI-Router. Here are some of the things I have attempted: Controller: $stateProvider .state('showViewA', { views: { ...

Accordion component in Angular UI Bootstrap tends to vanish unexpectedly when toggling between open and close states on Chrome version

I am facing an issue with placing a Google Maps directions panel inside an Angular-UI-Bootstrap accordion. Whenever I open and close the panel containing the Google directions, the panel disappears as shown in the screenshot here. The strange thing is that ...