Set values for scope variables that are created dynamically

I am currently working on a solution to toggle dynamically generated rows of data. I have attempted using ng-init and passing it to a function, but I seem to be making a mistake somewhere and struggling to understand if this is even feasible. The issue seems to lie in referencing the concatenated scope variable elsewhere. My setup involves Bootstrap 3 and AngularJS 1.5.

The HTML:

<div class="row" data-ng-repeat="equipment in task.equipment">
  <div class="col-md-12">
    <h4 class="green-text">
      {{ equipment.equipId }}
      <small class="green-text">
        <i class="glyphicon" 
          data-ng-class="{'glyphicon-triangle-bottom': field{{ $index }}, 'glyphicon-triangle-right': !field{{ $index }}}" 
          data-ng-init="equipment['field' + $index] = true" 
          data-ng-click="toggleTaskEquip('field{{ $index }}')">
        field{{ $index }}: MAKING THIS WORK IS THE GOAL</i>
      </small>
    </h4>
  </div>
  <div data-ng-show="field{{ $index }}">
          ...contents here...
  </div>
</div>

The JS:

$scope.toggleTaskEquip = function(toggleBool)
  {
    if (toggleBool === true)
      $scope.isTaskEquipOpen = false;
    else if (toggleBool === false)
      $scope.isTaskEquipOpen = true;
  };

Answer №1

It seems like you're looking to toggle the boolean value created in the ng-init on click.

Here's a possible solution:

<div class="container-fluid">
  <div ng-controller="MyCtrl">
    <div class="row" data-ng-repeat="equipment in task.equipment">
      <div class="col-md-12">
        <h4 class="green-text">
          {{equipment.equipId}}
          <small class="green-text">
            <i class="glyphicon" 
               data-ng-class="{'glyphicon-triangle-bottom': isVisible, 'glyphicon-triangle-right': !isVisible}"
               data-ng-init="isVisible = true" 
               data-ng-click="isVisible = !isVisible">I WANT THIS TO WORK</i>
          </small>
        </h4>
      </div>
      <div data-ng-show="isVisible">
        ...stuff here...
      </div>
    </div>
  </div>
</div>

You can skip using the toggleTaskEquip function on $scope.

Check out the JSFiddle here.

The ng-repeat directive creates a new scope for each template instance, allowing you to assign separate isVisible values for each equipment item by setting isVisible = true in the ng-init.

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

Tips for determining whether the current request is an AJAX request in MVC3 view using JavaScript

I have a div with a maximum height and overflow set to auto. When the size of the div overflows, a scroll bar is automatically added. However, I have also set $("#itemsdiv").scrollTop(10000); so that the scroll bar is always at the bottom. Now, I want t ...

Configuring Default Parameters in Angular's UI Router

Is there a way to set a default parameter for every route in Angular UI Router? In my app, users enter through another application by selecting a user and then navigating to my application. The URL in my application always includes the user ID so that use ...

How can I incorporate a CDN link into the newly updated Next.js App Router?

Exploring next.js has been quite an adventure for me, and I'm impressed with its capabilities. However, being a beginner, I have encountered some challenges. One issue I am currently facing is the difficulty in using Google icons without a CDN link in ...

A guide on incorporating dynamic formControlName functionality into AngularJs2

Currently, I am building forms using the form builder in AngularJS2. My goal is to incorporate the formControlName property/attribute into the form element as shown below: <input type="text" formControlName={{'client_name' + i}} placeholder=" ...

Oops! An error occurred: fs.readFileSync is not a valid function to perform the Basic

I'm facing a dilemma - I have a relatively simple app (I'm still new to Node): App.js import * as RNFS from 'react-native-fs'; var config_full; // readFile(filepath: string, encoding?: string) RNFS.readFile('./config.toml', ...

Alter the app's entire background color in React.js with a button click

I am facing an issue with changing the background color of my entire React App when a button is clicked. Currently, I am able to change the color of the button itself but not the background. I have imported the App.css file into my project and I am looking ...

Utilizing separate JavaScript files in Bootstrap 5: A guide to implementation

I am currently using Bootstrap, but I am looking to decrease the size of the Javascript files being used. My main requirements are dropdown/collapse and occasionally carousel functionalities, so I only want to include those specific scripts. Within the "d ...

Trouble with shadow rendering in imported obj through Three.js

After importing an object from blender and setting every mesh to cast and receive shadows, I noticed that the rendered shadows are incorrect. Even after merging the meshes thinking it would solve the issue, the problem persisted. It seems like using side: ...

Is it possible to send a message from a child iframe to its parent using HTML5 cross-browser compatibility

I've been following this tutorial on a video-sharing website, which demonstrates how to securely pass messages between an iframe and its parent. The tutorial can be found at a specific URL. To achieve this functionality, you would end up with a simila ...

Despite the presence of a producer and topic, sending Kafka messages is proving to be a challenge

Currently, I am using TypeScript and the KafkaJS library on my local machine with a single Kafka broker. After successfully connecting a producer, confirming the creation of my topic, and creating messages like so: const changeMessage = { key: id, ...

What is the best way to retrieve a JSON string in JavaScript after making a jQuery AJAX request?

Why am I only seeing {} in the console log when ajax calling my user.php file? $.ajax({ url: '.../models/user.php', type: 'POST', dataType: "json", data: {username: username, password:password, func:func}, succ ...

Capture cached images stored in the browser memory without relying on the source attribute of the <img> tag

Imagine you're managing a website, samplewebsite.com and you find that the images on it have been resized to very low quality. When you click on an image, you are directed to a 'view_image' page, for example samplewebsite.com/view?image=u ...

Managing Z-index (navigation) in Java Selenium 2.0 by addressing z-index conflicts prior to executing the built-in scroll function followed by the WebElement

When using Selenium 2.0, the .click() method has the capability to automatically scroll until the element is visible and can be clicked on, as shown in the code snippet below: WebElement box = driver.findElement( By.id( boxID ) ); box.click(); Generally, ...

Invoke a JavaScript function once the div has finished loading

After clicking on a radio button, I am dynamically loading a div element. I want to hide a specific part of the div once it is loaded. $(function($) { $('.div_element').on('load', function() { $('.textbox').hide(); } ...

Having difficulty entering text in the modal text box and updating it with a new state

Within my render method, I am utilizing the following model: { showEditModal && <Modal toggleModal={this.togglePageModal} pageModal={true}> <h2 style={{ textAlign: "center", width: "100%" }}> ...

Error encountered in Chrome while trying to fetch Next.js PWA with the use of next-pwa: Unhandled TypeError

Hello, I was recently working on a Next.js project and attempted to convert it into a PWA using next-pwa. To start off, I created the next.config.js file. const withPWA = require('next- pwa'); module.exports = withPWA({ pwa: { dest: ...

Javascript Steps to trigger a function when selecting the Stay on Page option in Google Chrome

If you're testing my code in the Chrome Browser, hitting refresh will prompt you with 2 options. Leave This Page Stay on This Page By clicking on the Stay on this page button, it should trigger my custom function displayMsg(). Can anyone pr ...

Executing multiple nested $http calls in Angular can significantly slow down the process

Within my angular application, I am currently dealing with 6 to 7 http chaining requests that are taking a significant amount of time to execute. What are some strategies for optimizing this process? empSvc.getallEmp().then(function (data) { if (dat ...

Troubleshooting a Basic jQuery Validation Problem

I've been attempting to incorporate the "Refactoring rules" segment from http://jqueryvalidation.org/reference/ However, I'm struggling to figure out the appropriate placement for the $.validator code. Currently, I'm inserting it like this: ...

Loading a Vue.js template dynamically post fetching data from Firebase storage

Currently, I am facing an issue with retrieving links for PDFs from my Firebase storage and binding them to specific lists. The problem arises because the template is loaded before the links are fetched, resulting in the href attribute of the list remainin ...