Attempting to make an API call within an ng-repeat loop is causing an error to arise in AngularJS, specifically reaching the limit of 10 $digest

I am encountering an issue with my scope function in the controller, where it calls an API to retrieve data from the database. The problem arises when I use this scope function within ng-repeat and run the application as it ends up getting stuck.

Here is a snippet of the view:

 <div class="col-xs-4 product-padding" ng-repeat="product in productList | filter:query | orderBy:'name'| offset: currentPage*itemsPerPage | limitTo: itemsPerPage " ng-cloak>
                <div class="theme-04-scope">
                    <div class="thumbnail">
                        <small class="defaultImageSize" ng-if="checkImageAttribute(product.ItemAttributes) == true">
                            <img class="ui-corner-all img-responsive defaultImageSize" ng-src="data:image/jpeg;base64,{{loadProductImage(product.ItemAttributes)}}" />
                            @*ng-src="/Product/LoadProductImage/{{loadProductImage(product.ItemAttributes)}}?width=200&height=144"*@
                        </small>

                    </div>

                </div>
        </div>

Angularjs controller code:

// Function to load product image.
    $scope.loadProductImage = function (itemAttributes) {
        var imageId = 0;
        $.each(itemAttributes, function (index, data) {
            if (data.AttributeId == 1000700 && data.DataXml != null) {
                imageId = data.DataXml;
                return false;
            }
        });
        productRepository.getProductImage(imageId, 200, 144).then(function (imageArrary) {
            $scope.itemIdArr.push(imageId);
            $scope.productImage = imageArrary;
        });

        return $scope.productImage;
    }

And here is the repository function:

 getProductImage: function (imageId, width, height) {
        var deferred = $q.defer();
        $http.post('/Product/LoadProductListImage', JSON.stringify({ id: imageId, width: width, height: height })).success(deferred.resolve).error(deferred.reject);
        return deferred.promise;
    }

Answer №1

Placing a function within view interpolation can lead to it being evaluated multiple times during each digest cycle, potentially causing performance issues. It is not recommended to include an API call in such functions.

.directive('displayProductImage', function ($http) {
    return {
        scope: {
            imageId: '@imageId',
            width: '@width',
            height: '@height'
        },
        link: function (scope, element, attrs) {
            console.info(scope.imageId, scope.width, scope.height)
            $http.post('/Product/LoadProductListImage', JSON.stringify({ id: scope.imageId, width: scope.width, height: scope.height })).success(function (data) {
                scope.productImage = data;
            });
        },
        template: '<img class="ui-corner-all img-responsive defaultImageSize" ng-src="data:image/jpeg;base64,{{productImage}}"></img>'
    }
});

This code snippet can be used in your view like this:

<span display-product-image width="200" image-id="200" height="144"></span>

Enjoy exploring the functionalities!

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

Django does not retrieve data using fetch()

I am utilizing the fetch() method to send an ajax request to my server. However, when I use request.POST, it returns an empty QueryDict instead of my actual data which is returned by request.body. Can anyone help me figure out what I'm doing wrong? B ...

When refreshing data, duplicate the d3 graph

When I try to update my d3 graph after selecting a site from the dropdown menu, a new graph is generated and I can't figure out how to remove the old one. https://i.sstatic.net/R5BNE.png Below is the code within the script tags: <script> imp ...

Error: The route configuration must include a "path" parameter when exporting imports in Vue Router

Important Information: The Index/Search/Features modules all share the same code structure, with different names. Each module consists of a path, component, name and meta as seen below. notes/routes/routes.js import Index from './index' import ...

Utilize React's debounce feature in conjunction with updating state using

Introduction Let's discuss the popular debounce function provided by lodash. Imagine a scenario where a user rapidly enters values like 1, 12, 123, 1234. The debounce function ensures that only one alert, with the final value 1234, is triggered afte ...

How can I detect the scroll action on a Select2 dropdown?

Is there a way to capture the scrolling event for an HTML element that is using Select2? I need to be able to dynamically add options to my dropdown when it scrolls. Just so you know: I am using jQuery, and the dropdown is implemented with Select2. The ...

Height fluctuations observed in Bootstrap Carousel

I am currently working with a react-bootstrap carousel component. The issue I am facing is that the carousel jumps when it scrolls due to the images having different sizes. If I try to fix this by setting the size with weight: 1309px and height: 730px, th ...

Steps for generating a JSON request from XPages to the Yandex Translate API

Can anyone assist me in creating a JSON request from XPages to the Yandex JSON interface API? I need help with configuring the HTTPS request for this specific API. More information can be found at this link. Additionally, I am looking for guidance on how ...

Is it feasible to impersonate a session in PHP by manipulating cookies on the client-side with JavaScript?

Is it possible for an unauthorized visitor to view, delete, or edit session cookies in a PHP web app if HttpOnly cookies are not being used? What happens when a user on a non-session page of a web app sets a cookie with the same name as a session page coo ...

How can one execute a function within an HTML attribute value using Angular?

I am currently attempting to use the weatherToFontAwesomeIcon(weatherDescription: string) function directly within the HTML file for this component. My goal is to showcase a specific FontAwesome icon based on the weather response from the API. import { Cur ...

The Veux Store is throwing an error message that says "Array is

When retrieving data from the Vuex Store, I start by checking if the array is present. Following that, my next step is to verify whether the noProducts object at index 0 exists. This validation process is important because the tweakwiseSortedProducts vari ...

From jQuery to HTML to PHP, then back to HTML from PHP through jQuery

Hey, I have a code snippet that I'm working on: <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script> <script type="text/javascript"> function get() { $.post(' ...

What could be the reason for the meta viewport not functioning properly on Android devices with Cordova 5.1.1?

Ever since upgrading my app to cordova 5.1.1, I've noticed that the meta viewport no longer functions properly on Android devices. The app is not displaying correctly as a result. Despite trying various solutions, I am still facing this issue. Is ther ...

Steps for retrieving data from mySQL and displaying it in a Modal:1. Connect to

I have encountered an issue with displaying records from my table columns named tid and ketprob. When clicking on a link, I am trying to show a modal that contains the data. The modal appears correctly but is showing no data. Can someone please assist me w ...

`UI-Router's stateChangeStart event is only triggered once``

I have set up my App.run method in the following way: $rootScope.AuthBag = { Authenticated: false, User: "", Roles:[] }; $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) { if (toState.authe ...

What is the most effective approach to seamlessly conceal and reveal a button with the assistance

I have two buttons, one for play and one for pause. <td> <?php if($service['ue_status'] == "RUNNING"){ $hideMe = 'd-none'; } ?> <a href="#" class="btn btn-warning ...

What is the process for publishing an npm package to a Nexus group repository?

After installing Nexus Repository Manager OSS version 3.2.1, I successfully ran it on my local machine. Setup Within Nexus, I have set up three NPM repositories: [PUBLIC] - acting as a proxy for the public npm registry [PRIVATE] - designated for my own ...

Record every action taken in the browser and compile it into a detailed HTML report

I am looking for a way to record and display all the browser actions performed in a test script in an HTML report. I am using protractor along with protractor-html-screenshot-reporter for reporting purposes. Is there any tool or API available that can he ...

Utilizing React to connect with Metamask and share the signer across various contracts

I'm currently working on a solution for sharing signers across multiple JavaScript files. In my walletConnect.js file, I successfully connect to Metamask and retrieve an ERC20 token contract. async function connect(){ try{ const accounts = awai ...

What is the best way to trigger a function once all asynchronous calls within a loop have been completed?

The function addData is called asynchronously within a loop every time reader.onloadend is triggered. const uploadFiles = () => { console.log(acceptedFiles) setLoading(true) console.log(loading) let i = 0 let l = acceptedFiles.length ...

Iframe not displaying Base64 encoded PDF in Chrome App

Currently, I am in the process of developing a Chrome App that essentially acts as a wrapper for the main app within a webview. The webview sends a Base64 encoded PDF as a message to the app, which then creates a hidden iframe and loads the PDF into the fr ...