Skipping an iteration in ng-repeat in Angular 1.0.8: A simple guide

Is it possible to skip a particular iteration in ng-repeat without modifying the underlying array/object being iterated over?

Consider the following example:

var steps = [
    {
        enabled: true
    },
    {
        enabled: true
    },
    {
        enabled: false
    }
];

Let's say we want to skip the third step based on the value of its "enabled" key. In a more recent version of Angular, we could achieve this with:

<div data-ng-repeat="step in steps" data-ng-if="step.enabled">

However, in version 1.0.8, ng-if is not available.

One approach I tried was creating a filter like this:

<div data-ng-repeat="step in steps | isEnabled" data-ng-if="step.enabled">

JS:

filter('isEnabled', function() {
    return function(input) {

        for(var i = 0; i < input.length; i++) {
            if(!input[i]['enabled']) {
                input.splice(i, 1);
            }
        };

        return input;
    };
})

However, this method alters the original step object, which is not ideal. I then attempted to clone the steps array:

filter('isEnabled', function() {
    return function(input) {

        var stepsBackup = angular.copy(input);

        for(var i = 0; i < stepsBackup.length; i++) {
            if(!stepsBackup[i]['enabled']) {
                stepsBackup.splice(i, 1);
            }
        };

        return stepsBackup;
    };
})

Unfortunately, this resulted in errors:

Error: 10 $digest() iterations reached. Aborting!
...

What could be the missing piece of the puzzle here?

Answer №1

There is no necessity to create a custom filter. AngularJS filters have the ability to filter based on properties when you provide an object as the filter: parameter. For example:

<li ng-repeat="step in steps | filter: {completed: true}">...</li>

Take a look at this example on JSFiddle, which I believe illustrates what you are looking for (it utilizes Angular 1.0.8):

http://jsfiddle.net/ck9u6/

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

Error: A semicolon is required before the statement in an HTML select tag

I am struggling with the code below in my java script: var i = 2; $(".addmore").on('click', function () { count = $('table tr').length; var data = "<tr><td><input type='c ...

Sorting through mongoose information on the front end using EJS depending on a dropdown pick

Beginner embarking on my inaugural project here. I have developed 2 Mongoose schematics and models for managing categories and products. The products are nested within the corresponding categories model. Using Node and Express, I successfully sent all ca ...

Choosing the perfect item with the help of a material's GridList

I've developed a react-mobx application using Material-UI, and the code structure is similar to this: render() { // defining some constants return ( <div> <img src={selectedPhoto} alt={'image title'} /> < ...

Leverage JavaScript E4X to cleverly rename specific XML elements

Currently, I am using JavaScript to manipulate XML without involving the DOM in a browser context. I need assistance with creating an E4X expression that can rename a list of tags based on a given substring. The challenge is that I may not know the exact t ...

Is there an efficient method for transferring .env data to HTML without using templating when working with nodejs and expressjs?

How can I securely make an AJAX request in my html page to Node to retrieve process.env without using templating, considering the need for passwords and keys in the future? client-side // source.html $.get( "/env", function( data ) {console.log(data) ...

Assistance with Redirecting Responses in Next.js API Routes

I'm currently working on implementing a login functionality in Next.js. I have made significant progress but I am facing an issue with redirecting to the homepage after a successful login. My setup involves using Next.js with Sanity as the headless CM ...

Implementing jQuery form validation including checking for the strength of the password

My understanding of jQuery was quite basic until I began working on jQuery form validation with password strength check. I successfully completed the password strength check portion, but now I am unsure of how to enable the submit button once the condition ...

The identification number is not used to update Mongo DB

When attempting to use the MongoDB driver in Node.js to update a document, I encountered an issue where the log indicated that the update was successful, but the data did not reflect the changes. Specifically, despite trying to update the document using it ...

Developing an autosave feature with AngularJS

My plan is to develop a directive that can provide an autosave feature to other directives by attaching it as an attribute. The idea involves creating a directive that sets up a watch on a specified model or attribute, utilizing the debounce function from ...

Identifying changes in Android volume settings via Progressive Web App (PWA)

After creating a PWA with React, I generated a TWA .apk using pwabuilder.com. While having a muted video playing on my screen, I am looking for a way to unmute the video when the user presses the volume change buttons on their Android mobile device. Is th ...

Add multiple checkboxes in a dropdown menu to save in a MySQL database

I have a register.php and I'm trying to insert the data into users table. The problem I have is with "languages" field - I've created a dropdown list with multiple checkboxs. I want the user of course to be able to insert to his profile more tha ...

By unplugging the # from the URL, I suddenly found myself unable to directly access my links

After deciding to remove the # symbol from my URLs in order to make them more user-friendly, I followed a tip from a question on Stack Overflow titled Removing the fragment identifier from AngularJS urls (# symbol). However, upon trying to directly access ...

The variable _spPageContextInfo has not been defined, resulting in a ReferenceError

The code in my JavaScript file looks like this: var configNews = { url:_spPageContextInfo.webAbsoluteUrl, newsLibrary: 'DEMONews', listId: '' }; // Attempting to retrieve the List ID $.ajax({ url: configNews.url + "/_a ...

The code functions correctly when retrieving information from a file, however, encounters issues when retrieving data

While working on my React application, I encountered a situation where I needed to read the value for translation from a file stored in the public folder. The files were saved at https://i.sstatic.net/oWXCh.png However, due to the dynamic nature of our d ...

How can you switch the display between two different class names using JavaScript?

I currently have a total of four filter buttons on my website, and I only want two of them to be visible at any given time. To achieve this, I labeled the first set of buttons as .switch1 and the second set as .switch2. Now, I've added a 'switch ...

Organize object properties based on shared values using JavaScript

Check out the JavaScript code snippet below by visiting this fiddle. var name = ["Ted", "Sarah", "Nancy", "Ted", "Sarah", "Nancy"]; var prodID = [111, 222, 222, 222, 222, 222]; var prodName = ["milk", "juice", "juice", "juice", "juice", "juice ...

loop through the links using their unique identifiers

Here is my current code in Jade/Pug: #pm_language.dropdown(aria-haspopup='true', aria-expanded='false') button#langbutton.btn.btn-primary.dropdown-toggle(type='button', data-toggle='dropdown') Lang [RU] ...

What is the best way to implement transition effects while toggling between light mode and dark in tailwind 2.0?

Currently, I am working on a small project utilizing tailwindCSS and have decided to incorporate a dark mode feature. To achieve this, I created a button that toggles the dark class in the html tag. However, upon testing the functionality, I noticed that t ...

Tips for extracting a value from a geojson response using a specific key

When analyzing the geojson response below, I am trying to access the following: Type and Segments To achieve this, I attempted the following: return data["type"] //does not work, error received return data["features"][0]["properties"]["segments"] ...

Switching PHP include on an HTML page using JavaScript

I've been attempting to modify the content of the div with the ID "panel_alumno" using a JavaScript function that triggers when a button is clicked. My goal is to display a different table each time the button is pressed, but so far, I haven't be ...