Using Angular JS to conceal a div within an ng-repeat loop

Looking for a way to hide a progress bar within an ng-repeat loop? You may be thinking about utilizing ng-hide, but running into issues with multiple iterations and divs sharing the same ID. The goal is to display the div when a user clicks on a button.

Any suggestions on how to achieve this? Thank you!

Daniel.


Edit. I initially didn't follow through with my original plan due to unexpected AngularJS behavior. However, after implementing it on Plunker, I found success.

I wanted to create a setup with two columns; one containing a button and the other featuring a progress bar. Clicking on the button in each row should reveal its respective progress bar. Initially, I believed AngularJS would display all progress bars due to having the same ng-hide tag ("bar" for example), leading me to post this question. For those interested in the code, feel free to check out the Plunker http://plnkr.co/edit/S5b0Dk0Tz7eZCkkJw95j?p=preview

Now that I have a better understanding of AngularJS behavior, I'm wondering how to hide the iteration with ID 5 when clicking on the button from iteration ID 3. Any ideas?

Thank you!

Answer №1

Consider adding an attribute called `isVisible` and utilizing `ngIf` or `ngShow` to toggle the visibility of div elements. Here's a straightforward example:

HTML:

<div
  ng-app="app"
  class="main-content"
  ng-controller="MainCtrl as app"
>
  <header class="header">
    <button
      class="button"
      ng-click="app.showAll()"
    >
      Show all
    </button>
    <button
      class="button"
      ng-click="app.hideOdds()"
    >
      Hide odds
    </button>
  </header>
  <div class="elements-container">
    <p
      ng-if="thing.isVisible"
      ng-class="{
        even: thing.even,
        odd: thing.odd
      }"
      ng-repeat="thing in app.stuff"
    >
      {{thing.content}}
    </p>
  </div>
</div>

Javascript:

(function (angular) {
  var
    app  = angular.module('app',[]),
    MainCtrl = function ($scope) {
      var
        len,
        thing,
        i   = 100,
        app = this;
      app.stuff = [];
      app.showAll = function () {
        len = app.stuff.length - 1;
        for (; len >= 0; len -= 1) {
          app.stuff[len].isVisible = true;
        }
      };
      app.hideOdds = function () {
        len = app.stuff.length - 1;
        for (; len >= 0; len -= 1) {
          if ((app.stuff[len].content % 2) !== 0) {
            app.stuff[len].isVisible = false;
          }
        }
      };
      for (; i >= 0; i -= 1) {
        if((i % 2) === 0){
          thing = {
            even: true,
            content: i,
            isVisible: true
          };
        } else {
          thing = {
            odd: true,
            content: i,
            isVisible: false
          };
        }
        app.stuff.push(thing);
      }
    };
  app.controller("e;MainCtrl& quote;, MainCtrl);
}(this.angular));

I hope this explanation is helpful, and here is a live demo.

update:

If I understand correctly, you want all progress bars to appear when clicking the button. In that case, ensure to declare the `bar` variable in a higher element within the controller instead of using `ngInit`. It is also best practice to initialize variables in the controller. Here's a modified version of your coding demo implementing these changes.

update 2:

To clarify further, let's delve into some detailed steps: In the HTML file, adjust the first two lines inside the body tag like so:

<body ng-app="app" ng-init="vari = [{_id: 2}, {_id: 5}]">
  <div ng-controller="ExampleCtrl" ng-repeat="data in vari">

Edit them to the following format:

<body ng-app="app" ng-controller="ExampleCtrl">
  <div ng-repeat="data in vari">

Within the JavaScript file, include this line:

$scope.vari = [{_id: 2}, {_id: 5}];

In summary, eliminate the ngInit directive, transfer the initialization to the controller to handle `$scope.bar`, and position the controller outside the ngRepeat scope for enhanced functionality.

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

What is the proper way to retrieve the rootScope in Angular?

When looking at this code snippet, the controller is given an injected scope and rootScope. However, an error occurs on the last line with: ReferenceError: $rootscope is not defined angular.module("myEntity").controller('productsCtrl', [ &a ...

Looking to dynamically load ng-model within an ng-repeat for a set of radio buttons

I am trying to dynamically load ng-model with data from an API call using ng-repeat for a series of radio buttons" This is my Controller: angular.module('app').controller('apiCallController', [$scope,'$http',function($scope, ...

Is it possible to incorporate Angular into a Jade template?

As a beginner in both Angular and Jade, I have been considering if it is possible to utilize Angular within a Jade template. So far, I have only come across examples of Angular being used with HTML templates and have not found any references to incorpora ...

Problems with alignment in Bootstrap

Struggling to master Bootstrap functionalities, I'm facing challenges when it comes to aligning my login form: <form name="signup" class="span8 form-inline" ng-submit="signup.$valid && IsSubmitEnabled && loginController.validateLog ...

How can I pass a parameter to a selector for an Ajax call when onClick event

Utilize a JQUERY AJAX call within a $(document).ready(function()..) function that iterates over MongoDB documents and dynamically adds HTML Div elements to the page using a .get Each Div includes a <button type='button' id='deleteItem&ap ...

Tips on displaying an array of elements as a <Dialog> within a <List>

I am currently developing a <ElementList> component that is designed to accept an array of elements through props and create a <List>, with each <ListItem> representing an element in the array. I have also included a separate component ca ...

Difficulty with Drag Events in Angular Bootstrap Calendar

I am encountering an issue with the drag event functionality of Angular Bootstrap Calendar. I am utilizing this link as a reference. Here is the HTML code snippet: <div ng-controller="scheduleCtrl as vm"> <div class="calender-mid"> <div ...

Stop Code Execution || Lock Screen

Is there a way to address the "challenge" I'm facing? I'm an avid gamer who enjoys customizing my game using JavaScript/jQuery with Greasemonkey/Firefox. There are numerous scripts that alter the DOM and input values. In my custom script, I hav ...

What is the reason behind not being able to utilize addEventListener on a variable that has been selected through DOM's getElementsByClassName method?

btn = document.getElementsByClassName('btn'); value = document.getElementById('value'); let counter = 0; btn[2].addEventListener('click', function() { if (btn[2].classList.contains('decrease')) counter -= 1; if ...

Creating a singly linked list in JavaScript that behaves like a single indexed array

I am faced with an array structure like this: var arrays = [ { "value": "$6" }, { "value": "$12" }, { "value": "$25" }, { "value": "$25" }, { "value": "$18" }, { "value": "$22" }, { "value": "$10" ...

What is the best way to reach a link using Selenium?

Challenge : Unable to interact with a link using JavaScript through Selenium. Attempted Solutions: element = driver.find_element_by_css_selector(a {href: "javascript:void(0)"}) resulted in a SyntaxError. element = driver.execute_script("ja ...

Waiting for Promise Js to be fulfilled

I've been exploring the use of Bluebird for handling promises in Node.Js. I have encountered a situation where I need a function to return only when a promise is fulfilled. The desired behavior can be illustrated by the following code snippet: functi ...

ReactJS - Divs enclosed within a sub component do not reflect state changes

Looking for help with my React class. I'm trying to change the class of the outermost div when menuClicked() is called, but it's not working as expected. Can someone provide insight into how state scope works in this situation? import React, {Co ...

How can I simulate the enter key being pressed for testing purposes using jQuery or pure JavaScript?

Is there a better method for simulating the user pressing the "Enter" key? I have tried using $(element).keypress() but it doesn't seem to capture the exact key pressed. This is specifically for unit testing purposes. ...

What is the best way to apply a class to a button in Angular when clicking on

Creating a simple directive with two buttons. Able to detect click events on the buttons, but now looking to add a custom class upon clicking. There is a predefined class: .red { background-color: red; } The goal is to dynamically apply this class whe ...

When utilizing AngularJS $resource, it sends an HTTP OPTIONS request in place of the expected HTTP POST when calling the

As I work on developing a basic library application in preparation for a larger AngularJS project, I have been exploring the benefits of using $resource over $http to interact with a RESTful API. While implementing $resource seemed promising for saving tim ...

Dealing with multiple ajax requests while utilizing a single fail callback

Looking for a solution: I have two arrays containing deferreds. In order to detect failures in the outer or inner 'when' statements, I currently need to use double 'fail' callbacks. Is there a way to consolidate errors from the inner &a ...

It seems that the maximum call stack size has been exceeded, resulting in a

Within this dropdown, I have incorporated a checkbox containing values in the form of an object. (refer to attached image) Every time I make a selection from the dropdown, there is a watch function that updates this new value, which is essentially an arra ...

Unable to execute two functions consecutively

After running the code, I encountered the error message Uncaught TypeError: object is not a function and only the status function is working properly. Can anyone help me identify the issue? $(document).ready(function() { steam('status', 60 ...

JavaScript method parameters are essential components that help define the methods

Can someone explain how function definitions work within a method in Javascript? An example I'm struggling with is in AngularJS: sth.controller('ctrlname', function ($scope, $ionicModal, par3, par4){ //code }); Another piece of code ...