Looking for the nearest element in AngularJS

I am attempting to create a slide toggle effect on the closest .contactDetails element when clicking on a. However, my current code is not producing the desired result.

<ul>
    <li ng-repeat="detail in details">
        <div>
            <a show-contact>{{something}}</a>
            <div class="contactDetails">
                <ul>
                    <li ng-repeat="another ng-repeat">
                        <b>{{something}}</b>
                    </li>
                </ul>
            </div>
            <br>
        </div>
    </li>
</ul>

app.directive("showContact", function () {
        return {
            restrict: "A",
            link: function (scope, element) {
                element.click(function () {
                    element.find(".contactDetails").slideToggle();
                });
            }
        };
    });

It seems that AngularJS might be having difficulty locating the closest .contactDetails, resulting in the failure of the slideToggle() function.

I have also attempted using

element.closest(".contactDetails")
, but this did not yield the expected outcome either. Any assistance would be greatly appreciated. Thank you.

Answer №1

Because the anchor tag is not within the div, using find won't work in this case. The closest method searches up the DOM, not down. Here's how I would approach it (just focusing on the link portion of the directive):

function(scope, element) {
    element.on("click", function() {
        element.next(".contactDetails").slideToggle();
    });
}

Check out the jsFiddle example

Answer №2

Behold the solution you requested --> Click to Run Snippet.

1) First, I target the .contactDetails element

var contactDetails = element.next();

2) Next, I execute the method

.toggleClass('hide')

on the .contactDetails element to toggle its visibility.

3) The ".hide" class sets display property to none;

display: none;

4) Now, an event listener is added to the element

 element.on('click', function () {
     //Code goes here               
 });

var myapp = angular.module('myapp', []);
myapp.directive("showContact", function () {
        return {
            restrict: "A",
            link: function (scope, element) {
                element.on('click', function () {
                  var contactDetails = element.next();
                    contactDetails.toggleClass('hide');                       
                });
            }
        }
});
                        
    
myapp.controller('MainCtrl', ['$scope', function($scope) {
  this.something = 'This is something';
  this.arr = ['mike', 'john', 'brian', 'joe'];  
}]);
body {
font-family: Arial, Tahoma;  
}
.hide {
  display:none;
}

a{
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
  <div ng-controller="MainCtrl as ctrl">
    <ul>
    <li>
        <div>
            <a show-contact>Toggle class (CLICK ME)</a>
            <div class="contactDetails">
                <ul>
                    <li ng-repeat="name in ctrl.arr">
                        <b>{{name}}</b>
                    </li>
                </ul>
            </div>
            <br>
        </div>
    </li>
</ul>;


    
  </div>
</div>

ere

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

Transmitting an Ajax request via property path

I'm experiencing issues with sending data to the server. Here is my Ajax call: $.ajax({ url: config.api.url, type: config.api.method, contentType: config.api.contentType, dataType: config.api.dataType, data: config.api.dataType === ...

Having trouble removing an element from an array while using the splice method within a jQuery $.each loop

Hey there, I have a particular object that contains a property named "contacts," its value being an array comprising of 4 objects with properties such as email, firstname, etc. My goal is to eliminate a specific object from this array by comparing its ema ...

My HTML form submission to the node.js file is stuck in an endless loading loop

As I work on setting up a basic form submission on my server to collect contact information, I run into an issue. The data is successfully received by my node.js server file upon submission but when I attempt to submit the form, the page tries to load the ...

Sorting with conditions in aggregations

My goal is to implement conditional sorting based on price, where I need to differentiate between two types of prices stored in the database: fixed price and bid. If sellType is fixed price, I want to retrieve the normal price. However, if sellType is bid ...

Custom calendar control vanishes on postback in ASP

After creating a custom calendar control that works smoothly for the most part, I encountered an issue. Whenever it is posted, the control disappears even when the user is still hovering over it. I want users to be able to change months, dates, or anythi ...

How can one effectively leverage Rails JS templates in their projects?

I'm struggling to understand the proper usage of Rails JS templates. Are they essentially replacing the success callback on an AJAX request? Why separate the JavaScript executed for a successful request from that of other callbacks? My assumption is ...

Connected Date Selector

I am new to using Bootstrap and attempting to implement a linked datepicker with the following requirements: Display only the date (not the time). The default selected date on page load should be today's date for both the Datepicker and the text ...

Encountering issues with saving information to MongoDB

I recently started working with the MERN stack and I am trying to save user information in MongoDB, which includes two string attributes: "name" and "role". However, I encountered an error in the browser console stating "Failed to load resource: Request t ...

A guide on getting the `Message` return from `CommandInteraction.reply()` in the discord API

In my TypeScript code snippet, I am generating an embed in response to user interaction and sending it. Here is the code: const embed = await this.generateEmbed(...); await interaction.reply({embeds: [embed]}); const sentMessage: Message = <Message<b ...

Implementing a Class on Page Refresh in Next JS

I am fairly new to using react and nextjs. How can I insert a script in a component to add a class when the page reloads? The code below doesn't seem to work because the page is not yet rendered when I try to add the class for the body tag. const Mode ...

Sending an associative array to Javascript via Ajax

Learning a new programming language is always a great challenge. Can someone guide me on how to efficiently pass an associative array to JavaScript using AJAX? Below is a snippet of code from server.php: $sql = "SELECT Lng, Lat, URL FROM results LIMIT ...

Code needed to efficiently include a d3 module through webpack

Having some trouble importing and using a d3 module in my webpack project. The function I need from the module is declared like so: https://github.com/d3/d3-plugins/blob/master/hive/hive.js d3.hive.link = function() { I attempted to follow this guide to ...

Form submission is not possible while the login form is active

I'm encountering an issue where I am unable to trigger - ng-submit or ng-click on this code except for the local onclick function on the login button. If you have any insights or solutions, please share them: <form ng-submit = "login.submitLogin ...

What is the best approach for incorporating multi-threading into my JavaScript code?

My website allows users to record canvas and also draw on the canvas at the same time. If users start recording the canvas and also start to draw on the canvas, the drawing on the canvas will lag. I have heard that multi-threading web workers should be abl ...

Guide on how to exit an async function

Here is the code I have been working on: myObject.myMethod('imageCheck', function () { var image = new Image(); image.onerror = function() { return false; }; image.onload = function() { return true; }; ...

Transforming a JSONP request to automatically parse a text response into JSON

If I have the following request $.ajax({ type: "GET", dataType: "jsonp", jsonp: "callback", jsonpCallback: "my_callback", url: my_https_url, headers:{"Content-Type":"text/html; charset=utf-8"}, success: function(data) { ...

What could be causing my redux-observable to not be triggered as expected?

Currently diving into the world of RxJS and Redux Observables within Redux, attempting to grasp the concepts by implementing a basic fetch example. This is how I've configured my store: import { applyMiddleware, createStore } from 'redux' ...

Creating a Border Length Animation Effect for Button Hover in Material-UI

I'm currently exploring Material-UI and trying to customize a component. My goal is to add a 'Border Length Animation' effect when hovering over the button. Unfortunately, I have yet to successfully implement this animation as intended. For ...

sent a data entry through ajax and performed validation using jquery

Is there a solution to validating the existence of an email value using ajax after validation work is completed? Despite attempting to check for the email value and display an alert if it exists, the form continues to submit regardless. See below for the ...

jQuery load() issue

$('form.comment_form').submit(function(e) { e.preventDefault(); var $form = $(this); $.ajax({ url : 'inc/process-form.php', type: 'POST', cache: true, data:({ comment ...