Apply the "ng-class" directive only if there is an <a> element located after the specified element

My issue involves a list of items categorized by labels, with a search filter applied. The problem arises when the labels appear in the search results even though the lists themselves are empty. I need to hide the relevant label if there are no items present. One way to achieve this is by checking if an anchor tag exists after the label with the class .item, and if it doesn't, then adding the .hidden class to the label.

I attempted the following Angular code, but being new to Angular, it didn't work as expected:

<div class="label" ng-class="next(a).length <= 0 ? 'hidden'">
  My Label
</div>

This is how a section appears when items are present in the list:

<div class="list search-list">
  <div class="label" ng-class="next(a).length <= 0 ? 'hidden'">
     My Label
  </div>
  <a class="item> .. </a>
  <!-- More a tags here -->

  <div class="label" ng-class="next(a).length <= 0 ? 'hidden'">
     My Label 2
  </div>
  <a class="item> .. </a>
  <!-- More a tags here -->
</div>

Upon inspecting, I confirmed that irrelevant anchor tags are indeed removed from the search results.

UPDATE:

I added a false case to the ng-class, but unfortunately, it didn't solve the issue.

<div class="label" ng-class="next(a).length <= 0 ? 'hidden' : 'shown'">
     My Label
  </div>

UPDATE2: Full structure

<ion-view view-title="Search">
  <ion-content ng-controller="SearchCtrl">

    <div class="list search-bar">
      <label class="item item-input">
        <i class="icon ion-ios-search-strong placeholder-icon"></i>
        <input type="text" placeholder="What are you looking for?" ng-model="searchFilter">
      </label>
    </div>

    <div class="list search-list">

      <!-- Group 1 -->
      <div class="item item-divider" ng-class="angular.next('a').length <= 0 ? 'hidden' : 'shown'">
        My Title
      </div>
      <a
        class="item item-avatar"
        href="#/app/{{item.link}}"
        ng-repeat="item in items | filter:searchFilter">
        <img src="img/item.png">
        <h2>{{item.title}}</h2>
        <p>Description</p>
      </a>

      <!-- Group 2 -->
      <div class="item item-divider" ng-class="angular.next('a').length <= 0 ? 'hidden' : 'shown'">
        My Title 2
      </div>
      <a
        class="item item-avatar"
        href="#/app/{{item2.link}}"
        ng-repeat="item2 in items2 | filter:searchFilter">
        <img src="img/item2.png">
        <h2>{{item.title}}</h2>
        <p>Description 2</p>
      </a>

    </div>


  </ion-content>
</ion-view>

Answer №1

If you prefer to stick with the original method of checking for the presence of an <a/> element after your <div>, you can create a custom directive. Below is an example that verifies this condition:


.directive('conditionalDisplay', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {

      if (element.next('a.item').length == 0)
        element.css('display', 'none');
    }
  }
});

Here's how it can be utilized:


<div class="list search-list">
      <div conditional-display class="label">
        My Label (Not Displayed, because there is no next a element)
      </div>
      <!--<a class="item"> .. </a>-->
      <!-- More a tags here -->

      <div conditional-display class="label">
        My Label 2 (Displayed)
      </div>
      <a class="item"></a>
      <!-- More a tags here -->
</div>

You can view a functional plunker at: http://plnkr.co/edit/ytCVxuBnbZAbX0faiQ4m?p=preview

Note: It's essential to have jQuery included for the next() selector to properly function, as JQLite does not support next() with selectors.

Personally, I find @pgreen2 's approach more aligned with the Angular way of handling tasks.

Answer №2

According to the documentation for the ng-init directive in AngularJS, you have the option to save the filter results and then access them as follows:

<!-- Group 1 -->
<div ng-init="filteredItems = (items | filter:searchFilter)" ng-if="filteredItems">
  <div class="item item-divider">
    My Title
  </div>
  <a class="item item-avatar" href="#/app/{{item.link}}" ng-repeat="item in filteredItems">
    <img src="img/item.png">
    <h2>{{item.title}}</h2>
    <p>Description</p>
  </a>
</div>

I encompassed the entire group within a div that utilizes ng-init to create a variable named filteredItems, which is later utilized in two other instances. Firstly, it determines whether to display the entire div using ng-if. This should address your initial query. Additionally, I employ filteredItems in the ng-repeat for the anchor tags.

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

Discovering the current state's name with AngularJS

I am trying to access the current state name in my run() function using $state.current.name, but it seems to be returning an empty string. $rootScope.$on('$stateChangeStart', function (event, next) { var json = (function ...

Concealing the text input cursor (caret) from peeking through overlaid elements on Internet Explorer

Currently, I am facing an issue with a form that includes a unique widget. This particular widget automatically populates a text input when it is in focus. The problem arises when the widget appears above the text input as intended. In Internet Explorer ...

Creating and deploying a basic Angular2 application in cordova

I have a pre-existing app developed in Angular2, which is quite basic. Upon attempting to build it for Android using Cordova, the debug build successfully installs on the system but gets stuck at the loading stage. I am seeking guidance on how to ensure th ...

Error: X does not conform to function definition

I'm currently in the process of developing a Vue application that interacts with Spotify's API to search for tracks. However, I've encountered an issue where I receive the following error message: Uncaught (in promise) TypeError: searchTra ...

Utilize Require.js to Load Dropzone.js Library

I am interested in integrating Dropzone.js into an application that is built using Backbone and Require.JS. However, I am unsure of the correct implementation process. Should I utilize require()? What is the most effective way to handle this integration? ...

Issue with Component not displaying properly upon refreshing

I'm currently using react.js and I have a button with an onClick event. My goal is to reload the page after clicking the button and then display a specific component on the page. However, I've encountered an issue where the component doesn't ...

How can users create on-click buttons to activate zoom in and zoom out features in a Plotly chart?

I am currently working on an Angular application where I need to implement zoom in and zoom out functionality for a Plotly chart. While the default hoverable mode bar provides this feature, it is not suitable for our specific use case. We require user-cr ...

Utilizing npm/buffer package within a TypeScript module

I'm interested in implementing this NPM package: https://www.npmjs.com/package/buffer I'm unsure about how to convert this line of code into typescript: var Buffer = require('buffer/').Buffer Could you provide me with the correct code ...

Tips for effectively downsizing an HTML Canvas to achieve high-quality images

Introduction I am currently facing issues with blurry visuals in my canvas animation, especially on devices with high pixel densities like mobile and retina screens. In order to address this problem, I have researched canvas down-scaling techniques and f ...

Offspring of div should have equal height without the top and bottom padding

Looking to ensure that the height of child divs matches the height of the parent divs. Currently, the divs expand as the page is resized. This is for search results, so there are multiple identical code blocks. function matchHeight() { $result = $(&a ...

Exploring the World of Node.js Event Handling in JavaScript

After reviewing the provided code snippet: binaryServer = BinaryServer({port: 9001}); binaryServer.on('connection', function(client) { console.log("new connection"); client.on('stream', function(stream, meta) { console.log(& ...

Run a series of promises in an array one after the other without relying on async and await

Imagine having an array filled with promises. Each element in this array represents a knex.js query builder that is prepared to be executed and generates a promise. Is there a way to execute each element of this dynamically built array sequentially? let ...

What is the best way to retrieve a value from an asynchronous method in Node.js that is using promises and also calling another asynchronous method?

I have created two methods for verifying the availability of data in a database and storing the data. The methods are as follows: function IfUserExists(userId) { logger.info(`Checking If ${userId} exists`); return new Promise(resolve => { ...

What are the differences between Angular's dynamic templating using compile and template function?

I am familiar with the purpose of each item in: compile vs link(pre/post) vs controller Now, consider this simple code: HTML <body ng-controller="mainController"> {{ message }} <div otc-dynamic=""></div> </body> Cont ...

Is it possible to trigger a function dynamically upon checking a checkbox?

I’ve been working on a simple string formatting app using React, diving into hooks as I go. Right now, I’m tackling the part where I need to trigger specific text formatting functions based on checkbox selections. Let's say, if the lowercase chec ...

Show the ajax response on a separate page

I am looking to showcase the output of an ajax request on a separate page rather than the page where the ajax call originated. The scenario is that I have a membership directory page, and when a user clicks on a member ID cell, an ajax call sends the ID to ...

Mastering Angular Protractor for End-to-End Testing

Currently working on an end-to-end test for my Angular application using Protractor. While I can mock httpBackend for unit tests, I prefer to make actual server calls and test against the JSON response. Despite researching on stackoverflow, I'm still ...

What is the proper method to set up jQuery in scripts loaded via AJAX? I keep receiving the error message: 'Uncaught TypeError: Object #<Object> has no method'

I have developed a website with an index page that contains a div for loading the content of each individual page. Initially, I included external JS files and performed initializations within each separate page. However, most of the time when the page loa ...

How to position an image on top of each printed page using HTML/CSS (SCSS)

I've created a simple and small webpage that looks like this: https://i.sstatic.net/R7Ajz.png Everything is perfect in the browser, with all the styles (margin, padding, etc.) just as I want it. However, my issue lies in the print view of the page. ...

Components in Angular are not compatible with Promises and Services

Encountering a peculiar issue with Angular Components interacting with a service. To elaborate, there is a basic service containing mock data as an array within. It includes two methods - one synchronous and the other asynchronous which returns a promise ( ...