The ng-class directive in Angular is failing to function properly within the ng-repeat loop

I am facing an issue where I am attempting to color some of the items in a list using Ionic framework. The array named somearray contains the indices that need to be colored red. However, no matter what I do, only the first index in the array is being colored. Can you help me identify the problem in the code below?


  <ion-list>
    <ion-item ng-class="{red : !somearray.indexOf($index)}" ng-repeat="todo in todos" class="item">
      <div>
        <button class="button button-block button-dark" ng-click="addNewForm($index)">
          {{todo.title}}
        </button>
      </div>
    </ion-item>
  </ion-list>

Answer №1

indexOf function will return -1 if the specified item is not found in the array, otherwise it will return the index of the element.

To ensure that the return value of indexOf is valid, you can check if it is greater than -1:

{red : somearray.indexOf($index) > -1}

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

app.controller('myController', function($scope) {
  $scope.todos = [{title: 'a'}, {title:'b'}, {title:'c'}, {title: 'd'}];
  $scope.somearray = [1,2];
});
.red {
  color: red;
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<div ng-app='app' ng-controller='myController'>
      <ion-list>
        <ion-item ng-class="{red : somearray.indexOf($index) > -1}" ng-repeat="todo in todos" class="item" >
              <div>
                <button class="button button-block button-dark" ng-click="addNewForm($index)">
                  {{todo.title}}
                </button>
                {{$index}}
              </div>
        </ion-item>
      </ion-list>
</div>

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

"Exploring the Angular 3 router's wildcard route matching feature

Why does the following route configuration always navigate to ** instead of the route for app/jungle? import {bootstrap} from '@angular/platform-browser-dynamic'; import { RouterConfig, provideRouter } from '@angular/<a href="/cdn-cgi/ ...

Generating a fresh instance from a pre-existing object using JavaScript

Currently, I am facing a challenge from devchallenges.io known as the Shoppingify challenge. After carefully reviewing the prompt, I started working on creating a model that should have a specific format when a request is submitted. { "user": 1 ...

The Stripe technique appears to not be classified as a Function type

I added stripe to my project using npm install --save stripe, but when I include the following line const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);, I receive a warning stating that the stripe method expression is not of Function ...

What is the response of Express when it encounters numerous identical asynchronous requests from the same origin?

Currently, I am utilizing Express.js for my project. There is an async function that performs a task that can take anywhere from 20 to 30 seconds to complete. Once the task is done, it increases a user's counter in the database. However, users are req ...

Tips for maintaining accessibility to data while concealing input information

Is it possible to access data submitted in a form even if the inputs were hidden by setting their display to none? If not, what approach should be taken to ensure that data can still be sent via form and accessed when the inputs are hidden? ...

Do you know the location of the .bowerrc file in an Angular app generated by Yeoman?

Currently, I am going through a tutorial (http://www.sitepoint.com/kickstart-your-angularjs-development-with-yeoman-grunt-and-bower/) that may be outdated. It mentions a .bowerrc file after running the command yo angular. However, when I tried to locate th ...

Error Encountered in Next.js: PDFtron Webviewer - Troubleshooting

I'm currently working on a website that incorporates a dynamically imported PDF viewer within the page. When running the code locally, everything operates smoothly with no errors. However, when executing the "npm run build" command, I encounter the fo ...

The jQuery datetimepicker fails to reflect changes made to the minDate property

I have encountered a datetimepicker object that was previously set up with the following configuration: $('#startDate').datetimepicker({ monthNames: DATE_TIME_MONTHS_NAMES, monthNamesShort: DATE_TIME_MONTHS_NAMES_SHORT, dayNames: DAT ...

The jQuery progress bar vanishes once .load() is employed

I have successfully implemented progress bars on my website. However, I am facing an issue when I reload the div using jQuery's .load() function. After the div is reloaded, the progress bars disappear, although everything else seems to be functioning ...

The error message "the property '_env_' is not found on the type 'Window & typeof globalThis - React / Typescript ERROR" indicates that the specified property is not present in the

I encountered an issue while working with React/TypeScript. When I perform this action within the component: <p>API_URL: {window._env_.API_URL}</p> The error message I receive is: property '_env_' does not exist on type 'Window ...

Using jQuery to import an external script into a React JS project

I'm looking to integrate an external JavaScript file (using jQuery) into a ReactJS project. While I found some guidance on this page, I am still encountering errors. The external JS file is named external.js: $(document).ready(function() { docu ...

What is the best way to dynamically validate the fields and generate an array?

Currently in my Angular application, I've successfully implemented a pivot table using pivot.js. Now, I am faced with the task of loading all the indexes from elastic search whenever the user switches the index. Once the index is changed, the corresp ...

Vue router is unable to verify the user's authentication

I have certain app routes that are supposed to be restricted to admins only. I've added requiresAdmin: true, to the meta of those routes, but for some reason it doesn't prevent other users from accessing them. Code Note: I've included comme ...

Guidelines for indicating whether a date string is in UTC or local time

In a scenario where a user selects 01/01/2017 on a UI control, it retrieves a Javascript date object as "Sun Jan 01 2017 05:00:00 GMT+0000" instead of a string... However, I specifically require the date part (01/01/2017) and in UTC format. C# provides a ...

What is the best way to apply changes to every class in JavaScript?

Check out this HTML and CSS code sample! body{ font-family: Verdana, Geneva, sans-serif; } .box{ width: 140px; height: 140px; background-color: red; display: none; position:relative; margin-left: auto; margin-right: auto; } .bold{ font ...

What is the best way to incorporate a Thymeleaf message stored in message.properties into my JavaScript file?

Is there a way to insert messages from a message.properties file into a javascript file similar to how it's done in an HTML file? For example, on my home page I have a title listed as: <h1 th:text="#{home.screen.title}"></h1> Where home ...

Tips on resetting v-model after changing select options

In my project, I have implemented a cascading select feature where the options in the second dropdown are dependent on the value selected in the first dropdown. This is achieved by using a computed property based on the first select to populate the options ...

IE9 encounters an error when using jQuery's .remove() function

While testing my website in IE9 using Firebug Lite, I encountered an issue. When attempting to run a basic command to remove a div, I received an error saying "TypeError: Object expected". The command I used was: $("#drag-hoverbox_you").remove(); Interes ...

The functionality of onClick and console.log seems to be malfunctioning on Nextjs

I'm currently learning NEXT but I've encountered some issues with certain functions "use client" import { useState } from 'react' export default function idk() { const [counter,setCounter]=useState(0) const add=()=> ...

Is it possible to reset the text within the text box when the form is being submitted using the load() ajax function?

I am working on implementing a comment feature where the data entered in the form is appended and displayed after submission. Here is my HTML form: <table> <tr><td>Name :</td><td> <input type="text" id="name"/></td&g ...