Displaying or concealing a div depending on information, without loading hidden data on AngularJS

One of the features in my application is a search page that loads data based on a user's query. The results, which appear in groups of 10, contain two fields that I need to toggle between dynamically: "imgs" and "smallImgs".

To clarify, if a result's smallImgs.length == true, then I want to display those images. If there are no small images available, then I want to display the regular imgs.

I am familiar with using ng-hide and ng-show in AngularJS, and I could use a basic true/false statement in the template to show or hide the imgs/smallImgs. However, it seems that even when using ng-hide, the data still gets fetched (including the image downloads).

The only solution I have considered so far is handling this logic in my controller when making the API call to fetch the data:

 $scope.itemSearch.get({query:$routeParams.query, page:$routeParams.page}, function(data){
    $scope.posts = data.posts;
    for(var i = 0; i<$scope.posts.length; i++){
      $scope.posts[i].imgs = testImgs($scope.posts[i]);
    }
  });

var testImgs = function(data){
  if (data.smallImgs.length){
    return data.smallImgs;
  } else{
    return data.imgs;
  }
}

However, I have not been able to make this work yet. Is this the most effective approach? Is there a more Angular-oriented way to handle this in the view?

Answer №1

To address this issue, my suggestion is to incorporate a new method in your controller:

$scope.fetchImages = function () {
    // Insert the necessary code to retrieve the accurate array here
};

Afterward, you can simply utilize this method in your view like so:

<div ng-repeat="image in fetchImages()" />

For a hands-on demonstration, feel free to check out this sample jsfiddle.

Answer №2

When using $scope.itemSearch.get({query:$routeParams.query, page:$routeParams.page}), be sure to check if it returns a promise before proceeding.

$scope.getImages = $scope.itemSearch.get({query:$routeParams.query, page:$routeParams.page});

<div ng-repeat="image in getImages" />

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 manually trigger a version change transaction in IndexedDB?

I have been working on a Chrome extension that uses the IndexedDB to store data client-side in an IDBObjectStore within an IDBDatabase. The data structure requires users to be able to modify the object store freely, such as adding new objects or modifying ...

Having difficulties accessing information from the HTML document

I face an issue with my code where I am unable to fetch the sectionID from tr. I want to retrieve the dynamic id of sectionID on each button click for deletion, but it always returns null. Below is the JQuery script: <script> $(function () { $(&apo ...

What issues are hindering the successful export of my Vue component packaged with npm?

I created a small local npm package called fomantic-ui-vue with the following main js file: import Vue from 'vue' // Import vue component import button from './elements/button/button.vue' import buttonGroup from './elements/butt ...

The ellipsis menu pops up next to the final video in the series of HTML videos

Currently, I am working on rendering HTML video tags for playing videos. However, I am facing an issue where the three dots menu is not appearing near the button that triggered it, instead, it displays near the last video's three dots. To illustrate t ...

Struggling with the task of assigning a glTF item to a separate layer within Three.js

Exploring the use of layers in Three.js. This script includes a sphere, a triangle, and a glTF object (car). I activated a second layer: camera.layers.enable(1); Assigned the sphere, triangle, and glTF object to layer 1: car.layers.set( 1 ); sphere.lay ...

Adjusting the height of an element in AngularJS based on its width dynamically

I am working on a table that is generated using ng-repeat, and I want to ensure that each td in the tbody is square. Since all the tds have an equal width, I only need to adjust the first one. However, the size of the table and td will change when the wind ...

The Typescript Select is displaying an incorrect value

Here's the code snippet I've been working with: <select #C (change)="changeSelect(zone.id, C.value)"> <option *ngFor="let town of townsLocal" [attr.value]="town.data" [attr.selected]="town.data === zone.town && 'selected& ...

Dealing with vertical overflow in a flex-grow container within Bootstrap 4

As a newcomer to HTML web layout (I must admit, I might be making rookie mistakes), I'm struggling with an issue that's been driving me crazy. Despite searching extensively, I haven't found a solution that fits my particular case. I'm ...

Is it possible to selectively hide the remove icon for certain files within the antd Upload component?

Is there a way to specifically hide the remove button in the Antd Upload component for files that meet certain criteria? I am aware of the "showRemoveIcon" prop which disables the remove icon for every file, but is there a way to do this for only one fil ...

Steps to create inactive HTML with a loading GIF displayed

When the sign-up button is clicked, a modal pops up. After inputting data, upon hitting the "sign up" button, I would like the actual popup's HTML content to become inactive and display a loading GIF icon in the center until an AJAX response is receiv ...

Unable to set the value of `this` when defining a string prototype

Having trouble assigning a new value to the this keyword within a string prototype definition. function testfunction(thisValue) { thisValue = thisValue || this; thisValue = "new test"; console.log(thisValue); this = thisValue; // ...

Activate CSS when the mouse is released

I have developed a tool with a console setup that can be toggled between minimized and maximized states upon clicking. However, I am facing an issue where the console automatically minimizes once it is maximized. What solutions can I explore to address thi ...

Looking to extract the full page source with Selenium and Node.js? Having trouble getting the complete source using driver.page_source as it

Having trouble fetching the full page source with Selenium web driver in Node.js I attempted using driver.page_source but it returns undefined in the console if(this.driver.findElement(By.id("ap_error_page_message")).isDisplayed()){ console.log(t ...

Tips for setting up a range slider for decimal numbers

I have implemented the following code for a range slider. It works perfectly fine for integer values like 1 and 100, but I am facing issues when trying to use decimal values. I attempted to substitute 1 with 0.1 but it did not yield the desired result. ...

What techniques are most effective for creating unit tests in a Node.js environment?

One of the challenges I am facing is writing a unit test for a module where I load a mustache template file. To tackle this, I am exploring the use of mocha, chai, and rewire. Below is an excerpt from my module.js: var winston = require('winston&apo ...

Having trouble extracting the video ID from a Youtube feed XML with jQuery

My goal here is quite simple - I have created a search result using a URL string with the YouTube API. When you visit the URL, you can view the XML returned without any issues. The specific URL is: https://gdata.youtube.com/feeds/api/videos?q=all the smal ...

What is the best way to transfer data in a JavaScript onclick event and then retrieve it in the click handler function?

I've been struggling with this issue for some time now. When researching the onclick JavaScript call, I noticed that sometimes it is written as onClick with a capital C, while other times it's simply onclick. The code I'm working on is part ...

Unsure of the best way to approach pagination using {$.getJSON, php image array} - seeking guidance on the right

Currently, my code is set up as follows: When a user visits a specific link on the page The $.getJSON function sends a request to a PHP script PHP uses scandir() to generate an array containing image names (eventually in the hundreds to thousands, ...

What is the syntax for utilizing cookies within the `getServerSideProps` function in Next.js?

I am struggling to pass the current language to an endpoint. Despite attempting to retrieve the language from a Cookie, I keep getting undefined within the getServerSideProps function. export async function getServerSideProps(context) { const lang = aw ...

The property '_renderItem' cannot be defined as undefined

Seeking assistance with my code... Could someone please help? $(document).ready(function() { //$('#search input[name="filter_name"]').attr("x-webkit-speech", "x-webkit-speech") $('#search input[name="input-search-menu"]').autocompl ...