Issue with AngularJS: ng-show does not properly update class when $interval is triggered

Attempting to utilize $interval from Angular to switch the currently visible item in a list using ng-show. Upon inspecting the HTML, it was noticed that Angular alters ng-show between true and false, but does not eliminate the ng-hide class. The HTML structure is quite straightforward:

<h1>Hello Plunker!</h1>
<div ng-controller="MyCtrl">
  <div>Iterator: {{i}}</div>
  <ul>
    <li ng-repeat="d in data" ng-show="{{i == $index}}">{{i}} - {{$index}} - {{d}}</li>
  </ul>
</div>

The app.js is also quite simple:

(function(){  
   var app = angular.module('MyApp', ['my-controller']);
})();

and my module/controller

(function(){
  var app = angular.module('my-controller', []);

  app.controller('MyCtrl', ['$scope', '$interval', function($scope, $interval){
    $scope.data = [111, 222, 333, 444];
    $scope.i = 0;
    var timeoutId;


    timeoutId = $interval(function(){
      $scope.i ++;  
      if ($scope.i >= $scope.data.length)
        $scope.i = 0;
    },
    1000);


  }]);
})();

Check out my Plnkr example here

Answer №1

The reason for the issue is that you are using interpolation ({{i == $index}}) to set the string "true"/"false" in the ng-show expression. Instead, it is better to provide the expression directly.

ng-show="i == $index"

Check out this example on Plnkr

To further clarify, take a look at the source code for ng-show

 scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
    // adding a temporary class for animation-specific ng-hide
    $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
      tempClasses: NG_HIDE_IN_PROGRESS_CLASS
    });
  });

The watch is registered on the attribute value, so when using interpolation, it sets a watch on "true" for the first item and "false" for the last three. However, since the value remains constant during the digest cycle, the watcher does not execute as expected. By using an expression instead of a static string, the evaluation happens every digest cycle, allowing the class to be added/removed accordingly.

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

display a message of achievement within the $http response

I am attempting to display a success message in the HTTP response for 3 seconds before redirecting the page. Here is the code snippet: <body ng-app='myApp' ng-controller='myCtrl'> <div class="col-lg-12 col-sm-12 col-xs-12 ...

Is there a way to distinguish the HTML Elements from the CSS elements and retrieve them individually?

I am working on achieving a specific task and this JS fiddle represents one part of it. Check out the JS Fiddle here alert($("#content")[0].outerHTML); When executed, this code returns the following DOM structure: <div id="content"> <div ...

Implementing Facebook conversion tracking when there is no distinct 'Thank you' page can be done by utilizing the onclick event

Currently working on incorporating Facebook conversion tracking into a Facebook Tab. To see the page, visit this link. The issue I'm facing is that a separate page does not load after the form has been submitted. Is there a way to execute a section of ...

Different ways to effectively utilize Ajax response data in a separate JavaScript file

I'm currently working on integrating Google Maps into my project. To retrieve map data, I'm using PHP along with AJAX for the response handling. Below is the AJAX code snippet: <script type="text/javascript"> $.ajax({ type: "POST ...

Leveraging await with jsmediatags

Is there a way to implement Async/Await with jsmediatags for retrieving id3 tags? I am struggling to make it work, the current response format is cumbersome. {onSuccess:..., onError:...} I am looking for something along the lines of, let tags = await j ...

How can you use JavaScript to create hyperlinks for every occurrence of $WORD in a text without altering the original content?

I've hit a bit of a roadblock. I'm currently working with StockTwits data and their API requires linking 'cashtags' (similar to hashtags but using $ instead of #). The input data I have is This is my amazing message with a stock $sym ...

POST request in Ajax with NodeJs/MongoDB/Mongoose causing an Uncaught TypeError: Illegal invocation

Whenever I attempt to make a POST request using Ajax/Jquery, I keep encountering an error in the console. The specific errors are on lines 67 and 31 in the createTeam.js file: $.ajax({ //line 67 sendInvitation(teamID,_companyName,teamName) //lin ...

The issue of printable html not causing a new page break on Firefox has arisen

Recently, I've been working on creating an HTML report that I need to print out. In order to achieve this, I decided to make use of AngularPrint plugin (https://github.com/samwiseduzer/angularPrint). However, I encountered a problem when trying to pr ...

Complete a form on an external website using either C# or Javascript

I am looking for a solution to automatically fill and submit a form from a specific URL, as I need to trigger this process from my domoticz. Despite attempting different methods like using AJAX or injecting JavaScript, I keep encountering issues with the S ...

Showing just the keys of a JavaScript object array using Angular

Check out this live code example on JSbin Can you show only the key from expression syntax in Angular? Specifically, the key being the word "page". And is it possible to do this from an array (even though they are the same word)? HTML <body ng-app="a ...

When attempting to print a Rectangle on my webpage using JavaScript and taking user input, I encountered an error stating that 'str' is not defined

I'm trying to implement a feature where clicking on the "try it" button will prompt the user for the number of lines and then print that many lines in the form of a rectangle. However, when I run my code, nothing appears on the DOM and there is an err ...

Having trouble getting Angular Filter to work within a directive expression?

I am currently working on a directive where I need to convert both the attribute and object name values to lowercase. I have tried using filters, as well as the $filter service, but it doesn't seem to be working. Can anyone please provide assistance i ...

Creating two variables that share an identical name

Can variables with the same name set outside of a function be called within the function? var a = $(window).width(); // This is the variable I want to call if(!$.isFunction(p)){ var a = $(window).height(); // Not this one alert(a); } FIDDLE ...

What strategies can I employ to optimize this code in RXJS and Angular?

Is it possible to streamline these nested arrays for more efficient execution after all subscriptions have been completed? I believe there may be a solution involving the use of pipes, mergeMaps, concatMaps, etc. this.teams = [ { Assignments: [{Id: ...

Simple method for renaming Object Keys in JavaScript using a given function

Below is a question that I have been presented with... function changeKey(student, keyToChange, translation) { } /* This function is designed to modify an object representing student data by changing a specified key into its English translation. For e ...

Use JQuery version 1.8 or above to link the mousewheel

Currently, my website is utilizing Jquery 1.8.3. Unfortunately, I am facing an issue where I am unable to bind the mousewheel with this version of jQuery, while the 1.4.2 version successfully binds the mousewheel. I am seeking a solution to overcome this ...

Attempting to utilize console.log to print the ID using jQuery

I'm having trouble retrieving the id from a div tag and logging it to the console, as it returns undefined. Any thoughts on why this might be happening? <?php $id = get_the_ID(); ?> <div class="about-cont" id="<?php echo $id ?>">< ...

The vital role of Package.json in the distribution of packaged products

I am currently uncertain about the purpose of package.json in relation to packaging. My understanding is that dependencies listed under dependencies will be included in the distribution package, while those under devDependencies will not be included. How ...

in javascript, how can you access the value of a parent object within a nested object?

Within the material ui framework, I am utilizing the createMuiTheme function to create a theme. How can I access the values of the parent object within a nested object? (I am aware that I can declare global variables above the function); To better unders ...

Using a static string in Javascript yields no issues, whereas working with variables can sometimes cause problems

I've been struggling with a problem this morning and it's time to ask for help! I have a JavaScript function that takes the value entered by a user into an autocomplete box, uses AJAX to send that value to a PHP script which then queries the data ...