The $scope variable is not retaining the value for the ng-repeat directive

I'm struggling to implement an ng-repeat on data fetched from an API in JSON format. The issue I'm facing is that even though I can see the data in $scope.wines when I console.log() before the function ends, the data seems to disappear by the end of the function. This is causing my ng-repeat="wine in wines" directive not to display correctly.

Here is the JavaScript code:

app.controller("MainController", function($scope){

        var api_key = "22x";
        $scope.wines = [];

        // Search Wine Function
    $scope.SearchWine = function(){
        $scope.wines = [];
        var search_api_url = "http://services.wine.com/api/beta2/service.svc/json/catalog?search=" + $scope.wine + "&size=200&apikey=" + api_key;
        var i = 1;

        $("#wine_list").html("");
        $(".loading").show();
        $(".alert").hide();
        $("input[type='text']").val("").focus();

        $.getJSON(search_api_url, function(data) {

            $.each(data, function(key, value) {

                if(key == "Products") {

                    $.each(value.List, function(k, v) {
                        $scope.wines.push(v);
                    });

                    console.log($scope.wines);
                    $(".loading").hide();
                }

            });
            console.log($scope.wines);
        });
        console.log($scope.wines);

    }; //End SearchWine


    });

and this is my HTML code:

    <div ng-controller="MainController">
    <header>
        <a href="http://powersearch.bestwine.com" class="brand">
            <img src="assets/images/logo.png" alt="">
        </a>
        <div class="col-md-6 col-md-offset-3">
            <form class="search_form">
                <div class="input-group">
              <input type="text" class="form-control" ng-model="wine" placeholder="Search by Winery or AVA...">
              <span class="input-group-btn">
                <button class="btn btn-primary" type="submit" ng-click="SearchWine()">Search</button>
              </span>
            </div><!-- /input-group -->
            <p class="help-block">You can also search international! Try typing in 'Burgundy'</p>
            </form>
        </div>
    </header>

    <div class="container">
        <div class="col-md-12">
            <table class="table table-hover table-bordered">
                <thead>
                    <tr>
                        <th class='text-center'>#</th>
                        <th>Wine Name</th>
                        <th>Wine Appellation</th>
                        <th>Wine Price</th>
                        <th>Favorite</th>
                    </tr>
                </thead>
                <tbody id="wine_list">
                    <tr ng-repeat="wine in wines">
                        <td>{{ wine.Name }}</td>
                        <td>{{ wine.Appellation.Name }}</td>
                    </tr>
                </tbody>
            </table>
            <div class="alert alert-info">Type in above to start.</div>
        </div>
    </div>

</div>

Console output when running the application:

Feel free to ask if you need more information!

Answer №1

Consider using $resource or $http for data retrieval instead of relying on jQuery $.getJson

For a more in-depth explanation, check out this resource: AngularJS: factory $http.get JSON file

It's recommended to steer clear of using jQuery in your Angular code, as shown below:

$("#wine_list").html("");
$(".loading").show();
$(".alert").hide();
$("input[type='text']").val("").focus();
...

Tasks like these can be better managed with Angular directives such as ng-show, ng-hide etc.

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

Is it possible to invoke the link function multiple times for a single directive instance?

Is it possible for the link function to be called multiple times in a single controller instance? angular.module('theApp').directive('theDirective', ['$http', '$interval', '$q', function($http, $interval, ...

How to implement JavaScript alterations for ng-routed files in AngularJS without using a controller

Looking for assistance with applying JavaScript changes to ng-routed pages in AngularJS without using a controller. <nav class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <div class="navba ...

Utilizing Jquery Plugins in Node.js with ES6 Imports: A Comprehensive Guide

I recently started using a jQuery calendar plugin, which can be found at this link: . I have been utilizing it with a CDN, but now I am looking to incorporate it as a Node.js module. What would be the most effective method to achieve this? Edit: Just to ...

Upon initiating a second user session, NodeJS yields contrasting MySQL outcomes

As a novice in NodeJS and Express, I find myself stuck on what seems to be a trivial issue. Despite my best efforts, I have been unable to resolve the problem on my own. My aim is to create a basic web application that allows user authentication and displ ...

Troubleshooting Problems Arising from PHP, Ajax, and SQL Integration

I've been encountering an issue that seems simple, but I haven't been able to find a solution specific to my problem in the forums. The problem arises when I try to display a table of hyperlinks, each linked to an AJAX method with an 'oncli ...

Minimize unnecessary rendering in React when toggling between tabs

I am currently working on a React application that utilizes material-ui to generate tabs. <div className={classes.root}> <AppBar position="static"> <Tabs value={value} onChange={handleChange}> <Tab label="Item One" /> ...

Ways to modify the pre-defined value in a TextField

I encountered a situation where I have a form with pre-filled data from a specific country. The data is initially read-only, but the user can click on the edit button if they wish to make changes. The issue arises when trying to edit the value in the Text ...

What steps can be taken to resolve the "npm ERR! code ELIFECYCLE" error in a React application?

After attempting to start my React app with npm start, an error occurred : $ npm start > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f3b3d2a212b3c0f7f617e617f">[email protected]</a> start C:\Users&bso ...

Utilizing the variable $this outside of an object context within an Ajax function

Encountering the following error: Fatal error: Uncaught Error: Using $this when not in object context in E:\xampp\htdocs\StudentGuideBook\Version1.0\models\AjaxChecking.php:4 Stack trace: #0 {main} thrown in E:\xampp&b ...

Retrieve the content of a text field with jQuery

Check out this block of HTML: <div class="sub-middle-column"> <div class="div-header">Grandsire <a "#", class="table-control-focus sub-header-table-focus" id="table-control-focus-t" >abc</a> <ul class="table-controls h ...

Learn the best practices for integrating the options API with the Composition API in Vue3

Using vue3 and vite2 Below is a simple code snippet. The expected behavior is that when the button is clicked, the reactive 'msg' variable should change. It works as expected in development using Vite, but after building for production (Vi ...

Ways to receive alerts when a marker enters a polygon

Looking for a way to receive notifications if my marker enters any of the polygons on the map. Having trouble implementing it correctly, here is my current code: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com ...

Can you provide me with the URL for the jQuery post function?

Could someone please clarify which URL I should use in the $.post call to the server for a node.js file? Most tutorials demonstrate with PHP files, but I'm unsure about calling node.js files. Should I post it to the app.js file or the route file? Thi ...

Displaying numerous information panels on Google Maps by extracting data from MySQL

Help needed! I've been struggling with this code for a while now. I can show multiple markers on the map but can't figure out how to display info details in a pop up box when they are clicked. Currently, I'm just trying to make it say "Hey!" ...

The error encountered in the Node crud app states that the function console.log is not recognized as a

I am attempting to develop a CRUD application, however, I keep encountering an error message that states "TypeError: console.log is not a function" at Query. (C:\Users\Luis Hernandez\Desktop\gaming-crud\server\app.js:30:25) h ...

How can HtmlUnit be used to identify and address website pages that display errors?

I've encountered an issue while trying to access this Ajax page through my Java program using the HtmlUnit 2.15 API. It seems that the problem arises from a broken link to a missing file located here. This is the snippet of code I'm working with ...

The search function on my blog is not displaying the blogs that have been filtered

I have encountered an issue with my code as I am unable to get any search results from the search bar. const RecentBlogs = ({recentBlogs}) => { const [query, setQuery] = useState("") const filteredItems = (() => { if(!query) return rec ...

Setting up a reverse proxy for deploying React applications

I am attempting to implement a setup where multiple containerized SPAs are deployed using a reverse proxy for routing. Each container contains a production build create-react-app served by an express app with the following configuration: app.use(express.s ...

Using Variables in JavaScriptExecutor with Selenium and C#

Currently in my Selenium tests, I am utilizing JavaScriptExecutor as shown below: IJavaScriptExecutor js = driver as IJavaScriptExecutor; string Pixels = "600"; js.ExecuteScript("arguments[0].style='transform: translateX(600px);'&q ...

Phantom.js: Exploring the Power of setTimeout

Below is a snippet of code that intends for Phantom.js to load a page, click on a button, and then wait for 5 seconds before returning the HTML code of the page. Issue: Utilizing setTimeout() to introduce a delay of 5 seconds leads to the page.evaluate fu ...