Updating route in AngularJS does not populate data (ngRepeat)

Just starting out and trying to figure things out, so bear with me if this is a basic issue.

I have two routes set up. localhost:3000 displays a list of objects, while localhost:3000/:slug shows detailed information about a specific product.

The initial listing works fine. You visit localhost:3000 and see the list of items.

listPhoneController.js:

angular.module('cmscApp').controller('listPhoneController', ['$scope', '$http', '$location', 'searchBoxFactory',
    function($scope, $http, $location, searchBoxFactory) {
        $scope.listInfo = searchBoxFactory;
        $scope.phoneList = [];

        $http.get('/api/getallphones').then(function(res) {
            $scope.phoneList = res.data;
        }, function() {
            $scope.errorMsg = 'Error in reaching data';
        });
}]);

list.html:

<!-- ... --->
<div class="result" ng-repeat="phone in phoneList | hasImageFilter:listInfo.imageRequired
                                                  | nameFilter:listInfo.phoneName
                                                  | priceFilter:listInfo.price.from:listInfo.price.to">
    <a ng-href="/phone.slug">More info...</a>
    <!-- ... -->
</div>

Clicking on the a tag takes you to the individual product's page (e.g. localhost:3000/samsung-galaxy-s4) and loads the information correctly. There's also a back button with a simple

<a ng-href='/'>Back</a>
.

However, upon returning back to localhost:3000, the list doesn't display. No errors are shown, but the `div`s are missing upon inspecting.

Could this be due to the asynchronous nature of $http, causing the page to load before retrieving the data? If so, why isn't the data binding as expected?

Here's my configuration:

angular.module('cmscApp').config(function ($routeProvider, $locationProvider) {
    $routeProvider
        .when('/', {
            templateUrl: '/pages/list.html',
            controller: 'listPhoneController',
            controllerAs: 'lpc'
        })
        .when('/:phoneSlug', {
            templateUrl: '/pages/detail.html',
            controller: 'detailPhoneController',
            controllerAs: 'dpc'
        })
        .otherwise({
            templateUrl: '/error/404.html'
        });

    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    });
});

Any suggestions or assistance would be greatly appreciated! I'm considering storing the data from $http in a factory to ensure it's loaded and updated every time the controller runs. Is that a good solution, or is there a better approach?

Answer №1

It appears that the scope was not binding correctly, prompting me to make adjustments to the $http.get().then() function:

$http.get(...).then(function(response) { 
    $scope.info = response;
    $scope.$apply();
}, function() { ... });

Hopefully this can help someone facing a similar problem.

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

What is the best way to include attributes in an HTML element?

I've been researching how to dynamically add attributes to an HTML tag using jQuery. Consider the following initial HTML code: <input type="text" name="j_username" id="j_username" autocorrect="off" autocapitalize="off" style="background-image: lin ...

Stop capturing mouse and keyboard events within a specific div element on all web browsers

I manage a website with forms that have jquery autosave features and are updated using ajax. These forms include various types of input elements such as textboxes, jQuery UI datepickers, and time pickers... <div id="content"> <form id="line1"&g ...

What could be causing my Google Chrome extension to only allow me to open 25 tabs instead of more?

Having a frustrating issue with my code that is causing problems when used as a Chrome Extension. Despite checking and confirming that the code should work correctly, it seems to stop opening pages after tab 25. I have verified that the code attempts to o ...

Is there a way to stop a setTimeout function in React before it is triggered?

In my application, I have set up a functionality where pressing a button starts the clock countdown. If no action is taken within 23 seconds (23000), the state changes to "this.state.user". This part is working correctly. However, if you click on the elem ...

Creating a customizable React application with an extra environmental setting

I'm currently working on an app that requires some variations. While the core remains the same, I need to customize certain parts of the app such as color schemes and images. My inquiry is: Is it feasible to construct an app with a specified instance ...

Adjust the text color of ASP.Net Label based on the presence of a hyphen

I need help changing the text and font color of my ASP.net label based on its content. The label displays a percentage change, and I want negative numbers to be shown in green and positive numbers in red. However, when I try to implement this, I keep enc ...

Incorrect color change on button triggered by onMouse actions and state fluctuations

While creating a user profile on my app, I encountered an issue with button coloring. When I try to add color functionality to the button, it turns red instead of green and remains red even when the mouse is not hovering over it. My goal is to have the but ...

What could be the reason behind receiving a 406 Not Acceptable status at the client side from the server, and why is my Spring controller not being triggered?

Here is the code for an AJAX GET request: $("#tabsss2").click(function tab1() { $.ajax({ type: "get", traditional: true, dataType: 'json', url: "DataGridServlet.htm", cache: false, ...

Attempting to confirm the accuracy of a data point within an extensive and interactive online table

I am facing a challenge in verifying a specific value from a large web table because none of the locators are unique and Selenium is unable to find all the elements. I am using Selenium and Cucumber JVM for automation. Below is a snippet of the HTML code ...

Issue with OnChange Not Triggering

Why isn't the onchange property firing when typing in my textbox? Check out the code below: VB.NET Dim textBoxUrlYoutube As New TextBox divUrlTextBoxContainer.Controls.Add(textBoxUrlYoutube) textBoxUrlYoutube.CssClass = "textboxyo ...

The error message UnhandledPromiseRejectionWarning is triggered due to a TypeError stating that the function authenticate is

Currently, I am attempting to incorporate basic authentication into my API project using Knex, Express, and MySQL. Here are the functions I have implemented: const users = [{ id:1, username:'selia', password:'fullservice'}] functio ...

Is there a way to present both Javascript and templates from parallel directories using express?

QUERY: Is there a way to modify the server.js file so that the three.js script in index.html does not display an error message like Cannot GET /node_modules/three/three.js? Code Snippet: index.html <!DOCTYPE html> <html lang="en"> <head&g ...

What is the best method for rounding a decimal number to two decimal places?

Here is the JavaScript code I am using: $("input[name='AuthorizedAmount'], input[name='LessLaborToDate']").change(function () { var sum = parseFloat($("input[name='AuthorizedAmount']").val()).toFixed( ...

Is memory allocated for 32 bits for variables with an undefined value in Javascript?

If I have a function with the signature below: function test(variable1, variable2) {} And I call it with only one parameter: test(5); Then within the test function, variable2 will be created but with a value of undefined. I'm interested to know if ...

State not getting updated with array passed to this.setState()

Within an array, I have stored the following credentials: //The Snippet variable is an array that looks like this { details: test, _id: "5d9d0b506ee7d03a54d8b1f6", name: "TEST GREEN", content: "<div style="background-color:green; height:100px; widt ...

Utilize range slider to refine dataset

I have implemented a jquery datatable along with the range.slider plugin. My goal is to apply the range slider to filter out data in the last column. In my attempt, I am using search.push to accomplish this filtering process. Below is an example of my i ...

JavaScript Code: Empty a text box when a different one is active

Looking for a solution to clear the content of one textbox when the user interacts with another in HTML and JavaScript. <input id="tb1" type="text" name="textbox1"> <input id="tb2" type="text" name="textbox2"> Seeking JavaScript code that wil ...

Accessing JSON files locally using JavaScript in IE and Firefox

I am a beginner in JavaScript and currently working on a small HTML page that will be run locally. I have a string in JSON format that I need to store and load as a file on the hard drive. I have managed to store the string using the following code snippe ...

Access the $event object from an Angular template selector

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script> <input type="file" #myFile multiple /> <button (click)="onDelete(myFile.event)">DeleteFiles</button> My code snippet is experienci ...

Encountering a problem with ng-repeat when working with a JSON

Having a bit of trouble displaying the keys and values from a JSON object in an HTML table using ng-repeat. The JSON object is coming from the backend, but for some reason, it's not showing up on the frontend. I know there must be a simple mistake som ...