Displaying and Concealing Elements with AngularJS and Implementing Alternating Styles

Within my collection of div elements showcasing product information, there is a need to display or hide specific fields based on the product type. While this functionality works smoothly, we now aim to enhance readability by implementing alternating row styles (zebra stripes). The challenge lies in maintaining the alternating styles even when certain rows are hidden, preventing the occurrence of consecutive rows with identical styles. The current HTML structure is as follows:


    <div style="alt-1">
       <div class="col-md-3 list-item-odd">Location</div>
       <div class="col-md-9 list-item-odd" >{{ location }}</div>
   </div>

   <div ng-show="itemType == 1" style="alt-2">
      <div class="col-md-3 list-item-odd">Layout Type</div>
      <div class="col-md-9 list-item-odd" >{{ layoutType}}</div>
   </div>

   <div style="alt-1">
      <div class="col-md-3 list-item-odd">Category</div>
      <div class="col-md-9 list-item-odd" >{{ category }}</div>
  </div>

The concern arises when itemType is not equal to 1, resulting in two adjacent rows styled "alt-1."

An approach I considered involves crafting a directive named alternate-styles with a lower priority to iterate through DIVs post ng-show (or ng-hide) execution.

<div class="enclosing" alternate-styles>

       The aforementioned HTML

</div>

However, uncertainties linger. Firstly, its effectiveness within an Angular environment remains uncertain, given the complexity of the framework. Secondly, I question whether my reliance on jQuery expertise blinds me to a more straightforward Angular solution.

Share your insights and recommendations,

Appreciate it,

Jerry

Answer №1

For those utilizing Angular 1.2, there is an alternative to using ng-show/ng-hide. Instead, you can employ ng-if which effectively eliminates the element from the Document Object Model.

Answer №2

Learning how to implement this directive was quite a challenge for me as I am still new to Angular. I struggled with the ng-show function triggering after the custom directive, causing some confusion. Fortunately, I came across a helpful blog post that explained the behavior of ng-show that I was observing. Below is the JavaScript code snippet for the custom directive and controller:

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

app.controller('MainCtrl', function($scope) {

  $scope.location = 'location here';
  $scope.layoutType = 'layoutType here';
  $scope.category = "category here"
  $scope.itemType = 2;
  $scope.alternateStyle = 0;
});
app.directive("alternateStyle", ['$timeout',
  function($timeout) {

    return {
      restrict: 'A',

      link: function(scope, element, attrs) {
        scope.$watch('itemType', function(newVal) {
          $timeout(function() {
            if (!element.hasClass('ng-hide'))
              scope.alternateStyle++;
            if (scope.alternateStyle % 2) {
              element.removeClass('alt-1').addClass('alt-2')
            } else {
              element.removeClass('alt-2').addClass('alt-1')
            }
          });
        });
      }
    };
  }
]);

For a working example, you can check out this Plunker sample.

I hope this information proves useful.

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 there a way to customize the cursor of the webkit resizer (pulltab)?

I'm having difficulty implementing a custom cursor on my webkit pulltab. While I am able to change other properties like background color, the CSS "cursor" property remains unchangeable: #sessionbuilder::-webkit-resizer { background: #000; cursor ...

Achieving Div Alignment in a Fluid Bootstrap Grid

I am currently utilizing the bootstrap grid system, as depicted below, and I am attempting to center some div elements (pic). Despite my attempts with various CSS properties like {margin:0 auto; width:50%}, I am unable to achieve the desired result. I fi ...

"Creating a custom comparator in Angular for sorting objects based on their keys

I am embarking on the challenge of designing a directive that will generate a dynamic table complete with front-end pagination and search functionality. It has become clear to me that in order for the search feature to work effectively, I must implement a ...

SVG is not extending to the entire viewport in mobile view

I need help with adjusting wave SVG's on my website to fill the entire viewport or screen width. Does anyone have any suggestions? To create the waves, I used a Wave SVG generator and placed them within a div element. <nav> <div> //align ...

What is the method for superimposing a div with a see-through input field?

I am currently designing a compact upload feature. It consists of a responsive element (actually a vue/quasar card) that adjusts in size according to the window dimensions and viewport. Within this element, there is a form containing an input field and a ...

Utilizing a Downloaded Font in CSS: A Step-by-Step

Just starting out here. I have a font file in .ttf format that I want to use on my blog, but I need help with obtaining its code. Am I on the right track? * { font-family: 'providence-bold'; src: url('/font/providence-bold.regular.tt ...

Struggling to make jQuery apply .css("display", "block") upon clicking a link

I am having trouble with getting jQuery to display CSS properties when a link is clicked on. After testing the CSS properties, I found that setting the display to "block" in the style sheet works as expected. However, if I set the initial CSS display to " ...

Take away the follow option on the embedded tweet

I need to customize the appearance of embedded tweets on a website by removing the follow button as well as the reply, favorite, and retweet buttons in the footer. Here is a simple HTML example: <blockquote class="twitter-tweet"> <a href="htt ...

There was an error loading the resource as the Object does not have the method 'adGallery'

For the past two days, I have been attempting to implement the jQuery plugin "ad-gallery" on my website without success. I must mention that my knowledge in JavaScript and CSS is limited, so the issue could be something simple. The peculiar thing is that ...

When using the background-blend-mode property, transition-duration is not taken into account

Try hovering over the top left h1 element in this code example You'll notice that it smoothly changes the h1 element to a shade of blue in just 2 seconds. However, the transition doesn't affect the blend mode of the backgrounds. Even though the ...

Fixed Element Transitioning from Starting Position on Scroll

Check out the JSFiddle example here I'm currently working on a website utilizing Bootstrap 3. I have an image that sticks to the page when scrolling by changing its position to fixed. While this functionality works, the image tends to shift slightly ...

I'm having trouble getting the height of my div element to render in percentage (%) in the CSS. Can anyone assist me with this issue?

When I try to set the "height" CSS property in percentage (%) for a div element, the HTML doesn't render anything. However, if I set the "height" CSS property using length values such as px or cm, it works perfectly fine. Can anyone provide assistance ...

Position a flash element adjacent to an input field

I'm struggling to properly align two elements together. Below is the HTML code: <input class='pretty-border' id='shareinput' value='afdsdasfdasfadsff' /> <span> <object classid="clsid:d27cdb6e-ae6-11c ...

Dependencies in Scala.js for CSS styling

I am currently having an issue implementing Scala.js with the bootstrap library. Including the js file was a simple and straightforward process: jsDependencies +="org.webjars" % "bootstrap" % "3.3.7-1" / "bootstrap.js" minified "bootstrap.min.js" However ...

Modify div content based on user selection

I have a question about updating the content of a div based on certain conditions in my code. Here is what I'm trying to achieve: <div class="form-control" ns-show="runningImport" disabled="disabled"> {{input[row.header_safe]}}{{select[row. ...

Finding a predecessor with Selenide through tag and class identification

Trying to find the ancestor element using Selenide library on a website. The ancestor element is <div class="BorderGrid-cell" ...>. The .closest(".BorderGrid-cell") method works well. However, the .closest("div.BorderGrid-ce ...

Adjust the width of the table's td elements

I am looking to create a table similar to the one shown above. Here is my implementation. Please review my JSFiddle. HTML: <table border="0" id="cssTable"> <tr> <td>eredgb</td> <td><a href="self">0 ...

Styling with CSS: Creating a scrollable gallery of images with a hover effect

I'm struggling to align multiple images horizontally on the page with a hover effect for each image. I can achieve one or the other separately, but not both together. As a beginner in HTML/CSS, I know it's a simple process. Below is my code with ...

Trouble with refreshing button after resolving routes in Angular UI Router

My Angular UI router is giving me trouble. When I navigate to the state below, everything works smoothly. However, if I refresh the page, the resolve function retrieves the data, injects it into the controller, but the view does not load. Essentially, th ...

Transitioning from Gulp 3 to Gulp 4: encountering issues with starting the http server using gulp serve

Within my AngularJS 1.7 project, I successfully upgraded my gulp configuration files from version 3.9 to 4.0.2. However, encountering an issue where the http server fails to start when running the command "gulp serve" I have made the following changes: C ...