AngularJS: accessing siblings by using the ng-click directive

I am currently working on a list (<ul>), which is being used in multiple instances within different ng-repeat iterations on the same page.

The initial list items are generated through ng-repeat, with the second to last item containing a span. When this span is clicked, it should reveal the final list item (which is initially hidden).

                  <ul ng-repeat="list in lists">
                    <li ng-repeat="item in getItems(a,b)">{{item}} 
                    </li>
                    <li>
                        <span style="cursor:pointer;" ng-click="display_item_form($event)" class="glyphicon glyphicon-plus"></span>
                    </li>
                    <li style="display: none;" class="item-form">
                      content that will be displayed when the 'button' is pressed
                    </li>
                  </ul>

While attempting different methods like passing $event and 'this', I have found that the outcome is always undefined or an exception.

    $scope.display_item_form = function($event){
//         alert($(it).parent().siblings('.item-form').attr('type'));//passing this instead of $event: result: undefined
            alert($($event.target).attr('type')); //undefined
//         $(it).parent().parent().children('.item-form').show();
//         $('.item-form').show(); // this works, but i only want .item-form inside the current <ul> to be shown

    }

Answer №1

If you want to create a variable on $scope when the page loads and then refer to it in the ng-if statement of the last li, here's how you can do that.

Keep in mind that: ng-if removes the element from the DOM based on the condition. ng-show hides the element by applying display: none; in the DOM.

It's important to remember this if you need to reinitialize any child components inside the conditional element.

Hope this explanation is useful! :-)

<ul>
  <li ng-repeat="item in getItems(a,b)">{{item}}</li>
  
  <li>
    <span ng-click="$scope.showContent = true"></span>
  </li>
  
  <li ng-if="$scope.showContent">
    content to be shown on 'button' press
  </li>
</ul>

Answer №2

You have the option to create something similar using only HTML.

showItem is initially undefined, so it remains hidden. When you click the button, it toggles the visibility (in this case, sets it to true) and will be displayed.

var app = angular.module("app", []);

app.controller("TestCtrl", ['$scope', function ($scope) {
   
  $scope.list = [{ val: 1 },{ val: 2 },{ val: 3 },{ val: 4 },{ val: 5 }];

$scope.list2 = [{ val: 1 },{ val: 2 },{ val: 3 },{ val: 4 },{ val: 5 }];
  
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div data-ng-app="app">

<div data-ng-controller="TestCtrl">
    <ul>
        <li ng-repeat="item in list">{{item.val}} </li>
        <li data-ng-click="showList1Item=!showList1Item"><span style="cursor:pointer;">+</span></li>
        <li data-ng-show="showList1Item">last item</li>
    </ul>

    <ul data-ng-controller="TestCtrl">
        <li ng-repeat="item in list2">{{item.val}} </li>
        <li data-ng-click="showList2Item=!showList2Item"><span style="cursor:pointer;">+</span></li>
        <li data-ng-show="showList2Item">last item</li>
      </ul>
    </div>
</div>

Answer №3

Here is how I resolved the issue:

angular.element();

$scope.show_item_form = function($event){
    var element = angular.element($event.target);
    element.parent().parent().find('.item-form').display();
}

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 a DOM lookup performed each time Vue's ref is utilized?

Exploring the capabilities of Vue.js, I have integrated a few refs into my current project. However, I am curious about the efficiency of calling refs in methods. Does Vue perform a DOM lookup every time a ref is called, or does it store all refs once for ...

CSS - Achieving full width on hover even when the element has a specified width setting

I am encountering an issue with my CSS. Although I have successfully centered everything, I am facing a problem with the hover effect in CSS. Whenever I apply the active class or hover over an li element, the background color expands to 100%. Additionally, ...

What is preventing the visibility of my invoice items when I try to make edits to my invoice?

Currently, I am utilizing Laravel 5.7 and VueJs 2.5.* in my project. The issue I am facing is related to a Bootstrap Model that I use for creating and editing TicketInvoice and its associated TicketInvocieItems. When I try to edit, the Bootstrap Model open ...

Ensuring the input field and button are positioned in a horizontal line

Currently, I am developing a to-do list application using React and Chakra UI. I am trying to align the input field and the button on the same line for a more organized layout. This is the current layout: image I aim to achieve a design similar to this: ...

In Javascript, swap out a particular colored region in an image with a different image

I've been scouring the internet in search of a solution to my problem, but it seems like I might not be looking in the right places. Imagine this image below, how can I replace the blue area with an image uploaded by the user? I'm struggling to ...

Is there a way to implement jwt.verify() from jsonwebtoken in a React application?

Every time I attempt to use the jwt.verify() or jwt.decode() function in my React project, it keeps throwing a multitude of errors. The errors that I encounter are: ERROR in ./node_modules/jwa/index.js 5:13-30 Module not found: Error: Can't resolve ...

Creating a unique icon using Jquery Mobile for a button in a PhoneGap application

Has anyone experienced issues with using a custom icon for a jQuery mobile button? I am having trouble as it is only showing a grey circle instead of the actual icon. The default icons work fine, though. Here is the code snippet from the index.html page: ...

The React render function fails to display the components it is supposed to render

Upon running npm start, the browser opens localhost:3000 but only displays a white page. To troubleshoot, I added a paragraph within the <body> tag in index.html. Surprisingly, the text Hello World! appeared for less than a second before disappearing ...

What is the best way to effectively clear memory in THREE.js?

After successfully rendering the model, rotating and zooming work perfectly. However, when attempting to clear the scene by clicking the button#clear, issues arise. The expectation is to traverse through the scene, add its children to an array, iterate ov ...

Angularjs update the <select> tag inside ng-if functionality

Looking for help to update the list of states based on the selected country. I've tried using $parent as recommended, but it's not working for me. Can someone guide me on how to populate the state select control? Also curious about handling mult ...

Vue.js: Awaiting Firebase to finish loading

I'm facing an issue with integrating Firebase into a Vue JS component. It seems like the firebase object loads after my component is created. Is there a way to ensure that Firebase is fully loaded before running any JavaScript code? For example, I w ...

Is the callback still triggered even after the off function is called?

Can someone help me with a scenario where despite calling the off on a reference, the callbacks are still being triggered repeatedly? var ref = new Firebase('https://example.firebaseio.com/123456'); for (var n = 0; n < 1024; ++n) { ref.pus ...

Ensuring Consistency in Array Lengths of Two Props in a Functional Component using TypeScript

Is there a way to ensure that two separate arrays passed as props to a functional component in React have the same length using TypeScript, triggering an error if they do not match? For instance, when utilizing this component within other components, it sh ...

Ways to eliminate active class in AngularJS

Once the active class has been added to an element, how can it be removed by clicking a button in a different function scope? ng-class="{active: $index == selected}" ...

JavaScript maintaining records and connections between multiple asynchronous events

I am working on an Angular 10 project where users can compress and upload images to Google Cloud Storage. The compression and uploading functionalities are functional, but I'm facing challenges with managing the asynchronous process of handling multip ...

How can I display a PHP variable in JavaScript?

I am having trouble displaying a PHP variable in Javascript; Below is the code I am using: <script type="text/javascript> $(document).ready(function (){ var n=<?php echo json_encode($count)?>; for(var i=0;i<n;i++){ var div ...

Retrieve JSON data from an external website

I am looking to display the number of players currently playing on a different poker website on my own site. The necessary data is provided in JSON format by this link (tournaments.summary.players). I have tried using a .getJSON request, but it seems like ...

Element with adhesive properties alters its color at a particular location

I need the sticky element to change colors at specific points and then revert back to its original color. The color should be orange initially, green on block 2, and orange again on block 3. For the complete code and to address any issues with jQuery, pl ...

Autocomplete's `getOptionLabel` function unexpectedly returned an object ([object Object]) instead of the expected string

Currently delving into the world of ReactJS and working with @mui controls, specifically a Multiselect Dropdown with autocomplete feature. Here is the child component causing me some trouble, displaying the following error message: "index.js:1 Materi ...

Verify information and send messages using JavaScript validation

I need assistance with my HTML form and JavaScript code. I am trying to send a parameter from the form to JavaScript in order to check if the input matches any values in an array. If there is a match, I want an alert message to be sent. However, the issue ...