Concealing individual items after generating them through ng-repeat

I'm currently working on incorporating a piano layout into my webpage by using two image files: one for white keys and one for black keys.

Although I've managed to create the images, I'm faced with the challenge of arranging the black keys in alternating groups of 2 and 3 while also hiding specific black key images at indices [1, 4(1+3), 8(4+4), 11(8+3), 15(11+4), .., 54]. I am seeking guidance on how to achieve this particular layout.

This is the code snippet I used:

HTML:

<div ng-controller="DrawCtrl as draw">
            <ul class="white-keys">
                <li ng-repeat="t in draw.range(56) track by $index">
                    <img ng-src={{draw.white_key}} />
                </li>
            </ul>
            <ul class="black-keys">
                <li ng-repeat="t in draw.range(55) track by $index">
                    <img ng-src={{draw.black_key}} />
                </li>
            </ul>
        </div>

JS:

angular.module('app')
.controller('DrawCtrl', function() {
    var self = this;
    self.piano_back = 'img/background.png';
    self.white_key = 'img/midi_white_up.png';
    self.black_key = 'img/midi_black_up.png';
    self.range = function(num) {
        return new Array(num);
    };
});

UPDATE: With the help of hansmaad's solution, I was able to resolve the issue.

HTML:

                <ul class="black-keys">
                <li ng-repeat="key in draw.keys" ng-switch="key.black">
                    <img ng-switch-when="true" ng-src={{draw.black_key}}  />
                    <img ng-switch-when="false" ng-src={{draw.black_key}} class="black-hidden" />
                </li>
            </ul>

JS:

    self.keys = [];
    var keyGroupOf3 = true;

    self.keys.push({black: true}); // first key is shown
    var i = 1;
    while (i < 54) {
        self.keys.push({black: false});
        // alwasy followed by at least two
        self.keys.push({black: true});
        self.keys.push({black: true});
        if (keyGroupOf3){
            self.keys.push({black: true});
            i += 4;
        } else {
            i += 3;
        }

Answer №1

If you're looking to create a keyboard in your controller using an array of keys, you can easily achieve this by utilizing a single ng-repeat to render all the keys. To display the appropriate image for each key, you have the option to employ ng-switch or store the image URL directly in the key object.

Here's a basic example that doesn't include images but makes use of ng-class:

http://plnkr.co/edit/kIvRqdkbHHNcUXKzSLZC?p=preview

<div ng-controller="DrawCtrl as draw">
    <ul>
        <li ng-repeat="key in draw.keys" ng-class="{ 'black' : key.black, 'white' : !key.black}">
        </li>
    </ul>
</div>

The controller function would look like:

function DrawCtrl() {
  this.keys = []
  for(var i = 0, e = 55; i < e; ++i) {
    this.keys.push({
      black: isBlackKey(i)
    });

  }

  function isBlackKey(i) {
    // Your piano logic here
    return i % 2 == 0;
  }
}

To utilize ng-switch, you could implement the following:

<ul>
    <li ng-repeat="key in draw.keys" ng-switch="key.black">
      <span ng-switch-when="true">Black key</span>
      <span ng-switch-when="false">White key</span>
    </li>
</ul>

Edit: Here's a simple algorithm to populate the keys array:

this.keys = []

var lastWasBlack = true;
var d = 5;
var next = 5;
for(var i = 0, e = 55; i < e; ++i) {

    var isBlack = !lastWasBlack;
    if (i === next) {
      isBlack = !isBlack;
      d = d === 5 ? 7 : 5;
      next += d;
    }
    this.keys.push({
      black: isBlack
    });

    lastWasBlack = isBlack;
}

}

http://plnkr.co/edit/kIvRqdkbHHNcUXKzSLZC?p=preview

Answer №2

Check out this Plunker example below where I haven't included any CSS, but you can still hide and show images using the provided link.

http://plnkr.co/edit/pgFKHShXpeS4EQhoaFTI?p=preview

<ul class="white-keys">
  <li ng-repeat="t in draw.range(20) track by $index">
    <img ng-src='http://lorempixel.com/g/50/15/technics' ng-hide="($index == 1 || $index == 4 || $index == 8 || $index == 11)"/>
  </li>
</ul>

I opted for ng-hide to control image visibility at specific positions. Does this meet your requirements? Feel free to reach out if it doesn't.

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

Execute JavaScript function after completion of CSS animation using jQuery

I'm working on an accordion feature that uses CSS animation to expand the clicked item. The expansion is triggered by li:target. However, I'm facing an issue where when clicking on an item, the scroll position doesn't align correctly with t ...

showcase every value upon submission in the form with options to edit and delete

Is it possible to display all values submitted in a form with edit and delete buttons? Currently, only one value is being displayed at a time. Whenever a new value is displayed, it replaces the old one. How can this be fixed? You can fin ...

Trouble fetching values from Google Sheets using getBatch method in JavaScript

Using javascript fetch() to retrieve a single value from a Google sheet works perfectly fine for me. However, when attempting to read multiple ranges, I encounter a 403 error. The following code executes without any issues: const apiKey = 'insert-you ...

The attached zip file is not being successfully downloaded by the client

I'm facing an issue with downloading a zip file in my MERN application. Although I receive the file in the response, the client fails to initiate the actual download process. My approach involves zipping files using archiver and then fetching them. A ...

What could be causing my scene to fail to render?

I'm attempting to adapt this particular example into CoffeeScript. Below is a snippet of my code: class Example width: 640 height: 480 constructor: -> @camera = new THREE.PerspectiveCamera 45, @width/@height, 10000 @cam ...

Ways to retrieve a specific object property from an array of objects within a click event listener?

I have instantiated multiple object constructors and stored them in an array which I loop over to display as a list. Now, I am trying to extract the name property from that list to use in an onclick event handler (not included in this code). I am unsure of ...

JavaScript scrollable selection menu with a favorite option button

I am looking to enhance a standard select element by adding a favorite button that can be toggled on and off for each option. Utilizing Bootstrap for styling, I want to create a user interface element that allows for smooth scrolling through the options an ...

Tips for concealing broken images in jQuery/JavaScript when generating dynamic content

Is there a way to hide the broken images in this dynamically generated HTML code using JavaScript? Unfortunately, I don't have access to the source code itself. I'm new to JQuery and could really use some assistance. Below is the snippet of the ...

Tips for validating a form that has been inserted using ng-include

Within a bootstrap modal window, I have 3 distinct form pages being dynamically inserted using ng-include. How can I efficiently handle validation for each form and successfully submit all three forms at once? HTML <div ng-switch on="page"> < ...

Comparing Jquery ajax object in Internet Explorer is not possible

Currently, I am utilizing jQuery's ajax function to fetch an HTML page. Upon success, a data object is retrieved. I aim to compare this data object to a string to determine the necessary actions. This functionality performs as expected in Firefox and ...

Error in jQuery and Canvas Image Crop: The index or size is invalid, exceeding the permissible limit

Recently, I downloaded and installed the Canvas Image Crop plugin from CodeCanyon but encountered a problem specifically on firefox. An error message kept popping up whenever I tried to upload certain images: "Index or size is negative or greater than the ...

The remove() function is failing to eliminate the element from all parent elements with the same class

I have a bunch of Wordpress posts. When the browser size is reduced to a certain point, I must relocate one specific element from each post to another element as per the design requirements. Here is the code I am using to iterate through each post and mov ...

Tips for adding a background image using React refs?

Seeking assistance with setting a background for a specific div using react ref, this is my attempted code snippet: The component class structure as follows: import React from 'react'; import PropTypes from 'prop-types'; import class ...

Having trouble with Google Analytics tracking file downloads? Possible placement issues?

Uncertainty looms over me as I question the correctness of my placement... Seeking guidance on this particular aspect... An intricately designed web application that dynamically generates a roster of accessible resources, flawlessly processes file info va ...

Create a personalized edit button for ContentTools with a unique design

I'm struggling to figure out how to customize the appearance and location of the edit button in ContentTools, a wysiwyg editor. After some research, I learned that I can use editor.start(); and editor.stop(); to trigger page editing. However, I want ...

Angular directive has issues with $compile functionality

This Angular directive automatically appends a new HTML item to the page every time my model changes: app.directive('helloWorld', function($compile) { return { restrict: 'AE', replace: true, scope:{ ...

How can I use ajax to validate a password that is shorter than 8 characters?

I need to validate the user's username and password to ensure they are at least 8 characters long. Previously, I used the onsubmit="return Validation()" attribute in the form, which worked fine. However, I am now submitting the form via ajax and I&apo ...

Encountering issues with styling the search bar using CSS and unable to see any changes reflected

I am currently working on creating a searchBar and customizing its CSS, but unfortunately, most of the styling properties seem to not be taking effect. So far, only changing colors seems to work as expected. .mainBar{ background-color: blue; width: ...

What is the best method to retrieve the country name from a world map using D3.js?

I'm trying to figure out how to retrieve the country name from a click event on the D3 world map. Despite inspecting the DOM, I can't quite understand how the country's name, code, or population is associated with the map. The template for ...

Developing numerous global objects within the context of JavaScript in Rails

I have an instance object called @cameras in my cameras controller's map method and am extracting necessary values from it for my specific purpose: + @cameras = load_user_cameras(true, false) + @map_data = [] + @cameras.each do |camera| + ...