Switching the ng-class in Angular with a click event

I'm having trouble modifying a class I've created based on a value from JSON, and then changing it when the user clicks on it.

Here's my code in the controller:

$scope.like = function(){
      if ($scope.class === "ion-ios-heart-outline")
        $scope.class = "ion-heart";
      else
        $scope.class = "ion-ios-heart-outline";
    };

And here's the element in the view:

<i ng-click="like()" ng-class="{ 'ion-heart' : article.like == 1, 'ion-ios-heart-outline' : article.like == 0}">

Answer №1

You have a slight mix-up with $scope.class and ng-class, as the former is not utilized in the view. To clarify, you can achieve what you want by implementing the following:

$scope.article.like = 0;
$scope.like = function() {
    $scope.article.like = $scope.article.like == 0 ? 1 : 0;
};

This will allow for dynamic changes to CSS classes based on whether the article has been liked or not.

Answer №2

Make sure to take a look at this plunker!

https://plnkr.co/edit/1LNxXlDRpzzZImspJJKE?p=preview

$scope.article= {}; 
$scope.article.like = 1;
$scope.like = function()
{
 $scope.article.like = ($scope.article.like === 0 ? 1 : 0);
};

It is important to note that the class should be set based on the value of article.like in the code provided above.

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

JavaScript Mouseover Custom Trigger with d3.js Library

Currently, I am experimenting with d3.js and am interested in creating a custom event with a unique trigger. From my understanding, the 'mouseover' event occurs when the mouse pointer hovers over a specific element both horizontally and vertical ...

Implementing HTMX with just one HTML page: A step-by-step guide

Just starting out with HTMX and created a sample: <!DOCTYPE html> <html> <head> </head> <body> <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfema ...

Subscription date is activated when a different part of the state changes in ngrx

Within my state, I have properties named start and end which store dates. Whenever any other part of the state is modified, the subscription for these start and end dates is triggered. Here is the subscription implementation: this.subs.sink = this.store ...

User interaction with a checkbox triggers a state change in Angular

Here is the code snippet I am working with, where clicking should set the checked value to false: @Component({ template: ` <input type="checkbox" [checked]="checked" (change)="onChange()"> ` }) export class AppC ...

Substitute this.bindMethod for function component

I have a class component that is structured like this: interface MyProps { addingCoord: any resetCoords: any } interface MyState { x: any y: any } class DrawerOld extends React.Component<MyProps, MyState> { width: number height: number ...

Linking Angular with property of an object

Is there a way to ensure that the binding of object properties works properly? For instance, in my controller I have: $scope.reviews = { rating_summary: 4, items: [ { title: 'A Title'}, etc... ] } And in my view: <li ng-repeat="review i ...

Utilizing Angularjs for image uploads

I've been working on this code for image uploading: $scope.uploadAvatar = function(e) { $scope.uploadAvatarError = false; $scope.uploadAvatarSuccess = false; var f = document.getElementById('uploadAvatar').files[0], fd = ...

How to extract only the truthy keys from an object using Angular.js

I am looking to retrieve only the keys with a true value in the data object and display them in the console with the specified format: Object { Agent=true, Analytics / Business Intelligence=true, Architecture / Interior Design=false } The catego ...

Calculating the bounding box of an Object3D with BufferGeometry in Three.js using JavaScript

Having an Object3D with various levels of children (more Object3Ds or Meshes/Lines), I am trying to compute a bounding box of the object and all its descendants similar to the setFromObject() method in the Box3 class. Unfortunately, I can't utilize t ...

ajax with names that are alike

I've set up a text input field that searches for file names on my server. However, it currently requires an exact match to display the file. I'm looking for a solution that can show me files even if the input text isn't an exact match. Here ...

Adjusting BackstopJS - Each scenario file is interpreted as an individual scenario rather than a group of scenarios in the configuration file

As I strive to scale BackstopJS by breaking down the original backstop.json file into a directory of structured scenario JSON files, I'm encountering an issue where the function in my config file interprets each JSON file as a single scenario instead ...

Ways to resolve the issue with the information window on Google Maps

I have a problem with displaying infowindows in Google Maps; currently, it only shows the information for the last marker added. let myLatlng = new window.google.maps.LatLng(-33.890542, 151.274856 ); let mapOptions = { zoom: 13, cent ...

Tips for modifying the color of a query term in HTML

Within my HTML file, I have <p class = "result"> {{searchResult}} </p> where {{searchResult}} represents the result of a search term. If I search for the term "hot", {{searchResult}} would display a string containing the word "hot" in a ...

Press the button to switch between displaying one component and hiding another component within reactjs

I am working on a project with two distinct buttons: one for grid view and another for list view. <button onClick={() => setClassName('jsGridView')} title="Grid View" > <IoGrid className="active" s ...

Tips for utilizing a select input type in redux-form

I've been struggling to implement a select input type in my react form using the redux-form library. While all other input types are functioning properly, I'm encountering issues with the select input when it comes to actions like initialize and ...

Trouble with serving CSS files using Express static directory

In my app.js file, I have the following code: app.use(express.static(path.join(__dirname, '../public'))); This code snippet is from my main layout page: <link rel="stylesheet" href="/css/styles.css"> Despite trying various combinations, ...

Retrieving information from the API to populate a child component in Next.js

I have been developing a header component and here's the code snippet: import style from '../../styles/header.css'; import '../../styles/globals.css'; export default function Header({data}){ const [showMe, setShowMe] = useStat ...

AngularJS showcasing data in a visually appealing layout

Successfully connected API and displaying data, but now encountering an issue with formatting the data into a table. When using ng-repeat="item in items", if used within a tr tag, only one row is shown. If used within a tbody tag, it repeats the tbody. He ...

Transfer files using Ajax and FormData technique

I have extensively researched various topics on this issue and prefer not to rely on any external plugins. function addToDatabase(menuItem){ var formData = new FormData(); formData.append("Description", document.getElementById("DescriptionID").value); ...

Encountering issues while trying to install Java using NPM

Encountering errors when attempting to run the following command to install java dependencies for NPM. NPM install -g java In need of assistance to fix this error. C:\WINDOWS\system32>npm i -g java [email protected] install C:\D ...