Does ng-class really allow the assignment operator? Could this be a bug or a hidden feature?

Noticed recently that the ng-class allows for assignment operators - is this a bug or a feature?

<li ng-repeat="cat in cats" ng-class="{active: cat = 'some-text'}">{{cat}}</li>

The correct usage would be:

<li ng-repeat="cat in cats" ng-class="{active: cat == 'some-text'}">{{cat}}</li>

For more details, check out the plunk behavior

Is allowing an assignment operator a bug or a feature?

Answer №1

This explanation focuses more on JavaScript expression evaluation rather than being specific to Angular.

var x;
console.log(!!(x = 'some-text'));

When you check your console, it will consistently display true. The same concept applies to

ng-class="{active: cat = 'some-text'}"
, which always sets the class to active because cat = 'some-text' will always evaluate to true.

Furthermore, each time the code runs, the value of cat will be updated to some-text. This means that your cats object will essentially just be an array containing some-text.

As @Mr_Perfect noted in the comments, if you want to conditionally assign active to your elements, use === instead of =.

Answer №2

The reason behind this is that when a value is assigned to the variable cat, it evaluates to true since cat is neither null nor undefined.

Answer №3

{'active': cat === 'some-text'} is the correct method for adding a class, where some-text is a string that, if matched with the variable cat, will add the active class to the li element.

You can also achieve this using:

ng-class="{(condition) ? 'condition_true_class' : 'condition_false_class'}"

UPDATE

<li ng-repeat="cat in cats" ng-class="{active: cat = 'some-text'}">{{cat}}</li>

In this scenario, cat="some-text" results in the string some-text, always being true and adding the active class to the li element. The value of cat within {{}} becomes some-text due to the assignment operator.

<li ng-repeat="cat in cats" ng-class="{active: cat == 'some-text'}">{{cat}}</li>

Here, if the value of cat matches with some-text, the active class is added to the li element. The value of cat remains unchanged since you are using the logical operators == or ===.

Answer №4

If you want to incorporate the "active" class with ng-class, here's a solution:

<li ng-repeat="cat in cats" ng-class="{'active': cat == 'some-text'}">{{cat}}</li>

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

ReactAwesome Slider Autoplay Feature

I've been tinkering with a React Awesome Slider that you can find here: https://github.com/rcaferati/react-awesome-slider I've managed to implement it successfully, but I'm struggling to make it autoplay every 10 seconds. I assume I need to ...

Accessing XML content within a web browser

I am facing an issue with parsing a string in JavaScript. var output = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><abc><xyz><xyzResponse><URL>http%3A%2F%2Flocalhost%3A8080%2Fnet%2Fxyz.do%3Fpartner%3Ddummy%26 ...

What is the best way to track the total time spent on a page over multiple visits?

I am interested in measuring the time spent by a user on a process flow over multiple sessions. While I have come across information regarding single-session tracking, figuring out how to track multiple sessions seems quite complex. For example, let' ...

Issue with Material-UI NativeSelect not correctly displaying preselected option

I have the following code snippet: <NativeSelect classes={{ icon: classes.icon }} className={classes.select} onChange={this.onVersionChange} > { Object.keys(interface_versions).map(key => { return <optio ...

Utilizing SVG within Sproutcore allows for seamless access to DOM nodes and the ability to effortlessly bind Sproutcore events directly to the DOM

Exploring Sproutcore, I am delving into the world of SVG (Standard Vector Graphics) integration within the app. The goal is to utilize a canvas for drawing elements like lines, boxes, and images, all of which SVG offers. My approach involved incorporating ...

How can one display blog data (stored as a PDF) from a database alongside other different results (stored as

I have successfully displayed a PDF file from my database as a blob using the header("Content-type:application/pdf") method. Now, I am looking to also display some additional string results along with this PDF file. Is it feasible to achieve this while d ...

The results generated by the Google Maps API are consistently consistent

const request = require('request'); var geocodeAddress = (location) => { var encodedLocation = encodeURIComponent(location); request({ url: `http://www.mapquestapi.com/geocoding/v1/address?key=APIKey&location=${encodedLocation}` ...

Removing elements based on the size of the display

I need assistance with a JavaScript issue. I have a table with 2 rows and 5 columns, each column representing a day of the week with a specific class. The goal is to detect the current day based on the browser's width/height and remove all elements in ...

Utilizing the .fadeToggle() function to create a fading effect for text, which fades in and out

I am on the verge of achieving my goal, but I could use a little more assistance with this. $('.change').hover(function() { $(this).fadeToggle('slow', 'linear', function() { $(this).text('wanna be CodeNinja' ...

Submitting a form in Rails without refreshing the page and dynamically updating the view

Hello everyone! I am currently utilizing Rails and in my process, I would like the user to perform the following steps on the same page: Input their address Completing the form Submit the form Clicking to submit Update the view to display the add ...

Troubleshooting a TypeScript Problem with React Context

In my AppContext.tsx file, I have defined the following import React, { useState, createContext } from "react"; import { Iitem } from "../utils/interfaces"; interface AppContext { showModal: boolean; setShowModal: React.Dispatch< ...

Angular 1.3.10 encountered error: [$injector:modulerr] - Uncaught Exception

The application currently has limited content, resulting in this basic error. The use of ui-router is causing the issue. Here are the code snippets from different files: app.module.js: 'use strict'; angular .module('app', app); ...

Updating the position attribute of a mesh in Three.js using boxGeometry

I am currently working on a project that involves resizing a cube by clicking and dragging its faces. My approach is to update the position attribute on the buffer geometry object, and then either recreate the mesh or set the needsUpdate flag to let it up ...

Guide on how to showcase JSON data using vanilla JavaScript within the Laravel framework

As a beginner in Laravel, I am looking to pass JSON data from my controller using vanilla JavaScript to my view blade. However, I am unsure of the steps to accomplish this. Below is an example of my controller: public function index(Request $request) { ...

Sending $scope over AJAX, with only a limited number of variables being passed

Trying to send a variable through AJAX to an API. Below is the angular controller code: $scope.register = function() { _.each($scope.photos, function(images) { $upload.upload({ url: '/api/indorelawan/timaksibaik/register/uploa ...

React is throwing an error message stating that setCount is not a valid function

Getting an error saying setCount is not a function. I am new to this, please help. import React, { memo, useState } from "react"; export const Container = memo(function Container() { const { count, setCount } = useState(0); return ( ...

Having trouble adding items to an array within a Javascript promise

I am facing an issue with the exported function in a Nextjs app, which acts as an API page. The problem arises when the 'domainnames' array returns nothing in the 200 response. Interestingly, if I exclude the 'GetDomainStatus()' funct ...

A simple guide to running Express Js and MongoDB from the command line and gracefully closing the terminal

Is there a way to run an Express project without the terminal being visible or easily closed? I need my server to stay running, but I don't want the user on the local PC to be able to see or close the terminal. Any suggestions on how to achieve this ...

Reading data from Firestore in Next.js

I came across a Next.js starter that retrieves data from Firestore v9, but it only displays the data after a click event. How can I modify this code in Next.js to automatically show the data without needing to click? import { db } from '@/lib/firebase ...

Cancel an AJAX request without interfering with the subsequent request

When working with a number input and the "onChange" event, I have come across an issue with my ajax request. Upon aborting the request, it seems to have a negative impact on subsequent requests. If I send just one request without aborting, everything runs ...