Using the ng-class directive to dynamically set classes based on the value returned from

I am facing an issue with setting the icon style based on a value returned from the controller. The console log confirms that the value is triggered correctly, but it appears that there is a problem with the Ng-class expression. Any assistance on this matter would be greatly appreciated. Thank you in advance.

Controller Code

$scope.class = "favorite_border";
    $scope.changeClass = function(){
    if ($scope.class === "favorite_border")
        $scope.class = "favorite";
     else
        $scope.class = "favorite_border";
      console.log($scope.class);
    }

View Code

<i ion-ripple ion-ripple-color="#ff0000"class="material-icons" style="font-size: 32px" ng-click="changeClass()" ng-class="'{{class}}'== favorite_border ? 'favorite_border' : 'favorite'"> {{class}}</i>

CSS Style

.favorite_border{ color:gray};.favorite{color:red};

Answer №1

To adjust your display, follow these steps:

<i ion-ripple ion-ripple-color="#ff0000"class="material-icons" style="font-size: 32px" ng-click="swapClass()" ng-class="class === 'preferred_border' ? 'preferred_border' : 'preferred'"> {{class}}</i>

Alternatively, you can modify it according to the code in your controller above:

<i ion-ripple ion-ripple-color="#ff0000"class="material-icons" style="font-size: 32px" ng-click="swapClass()" ng-class="class"> {{class}}</i>

Answer №2

When evaluating conditions, avoid using an expression directly. Modify it as follows:

<i ion-ripple ion-ripple-color="#ff0000"class="material-icons" style="font-size: 32px" ng-click="changeClass()" ng-class="class === 'favorite_border' ? 'favorite_border' : 'favorite'"> {{class}}</i>

DEMO

.favorite_border{ color:yellow};.favorite{color:red};
<html>

<head>
  
<body>
  <div ng-app="app" ng-controller="ctrl">

    <i ion-ripple ion-ripple-color="#ff0000"class="material-icons" style="font-size: 32px" ng-click="changeClass()" ng-class="class == 'favorite_border' ? 'favorite_border' : 'favorite'"> {{class}}</i>
  </div>


  <!-- Angular Material Dependencies -->
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.6/angular.js"></script>
<script>
    var app = angular.module('app', []);

    app.controller("ctrl", function($scope) {
       $scope.class = "favorite_border";
      $scope.changeClass = function(){
      if ($scope.class === "favorite_border")
        $scope.class = "favorite";
     else
        $scope.class = "favorite_border";
      console.log($scope.class);
     }
    });
  </script>
</body>

</html>

Answer №3

To modify it, simply make the change to

ng-class="class == 'favorite_border' ? 'favorite_border' : 'favorite'"

You could also use

ng-class="class"

Just ensure that you initialize $scope.class='...' with the appropriate initial class value.

Explanation:

The logic within the ng-class directive operates similar to JavaScript expressions, with variables prefixed by $scope. So, when evaluating your expression:

'{{class}}'== favorite_border ? 'favorite_border' : 'favorite'

this will be interpreted as:

'{{$scope.class}}'== $scope.favorite_border ? 'favorite_border' : 'favorite'

leading to:

''== $scope.favorite_border ? 'favorite_border' : 'favorite'

initially, till the class is toggled, then

'favorite_border'== $scope.favorite_border ? 'favorite_border' : 'favorite'

In this context, neither of these conditions hold (resulting in

false ? 'favorite_border' : 'favorite'
==> 'favorite') and will not output the desired class name.

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

React App stalled due to continuously running function

In this section of my React app, the createBubbles function is functioning properly. However, I am encountering an issue where the entire app freezes when navigating to another page after visiting this one. The console displays the following errors and de ...

Stopping a JavaScript promise.all() based on a certain condition

Here's a snippet of code I'm working with: let promiseList = [] for (let i in data) { let promise = checkIfMember(data[i].tg_id, chatId).then(res => { if (res) { //if the user has a undefined username ...

Sophisticated method for implementing dynamic components with props in Vue

In a specific scenario, I am using an API to output all the content for my Page, including its structure. To provide context, imagine a CMS with a page builder feature where authors can place components via drag and drop to create pages, which are then del ...

One way to add a JSON object to an empty JSON array using Javascript involves pushing

Currently, I am facing an issue with an empty JSON array. shoppingCart: [] In addition to the empty array, I also have a JSON object defined as follows: let product = {"name": "name", "price": "price", "quantity": "quantity", "logoPath": "logoPath"}; M ...

The Dropzone feature fails to function properly when displayed on a modal window that is being shown via

After attempting to integrate Dropzone and JavaScript into a Bootstrap Modal called through AJAX, I encountered issues. Due to the high number of records, I avoided placing the Modal in a foreach loop and instead used AJAX to call a controller method upon ...

Retrieve the specific file path of a dependency within the node_modules directory

Can you help me find the exact path of a dependency within a specific node_modules package? Here's an example setup: |- node_modules/ |- <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4a4b5b7bfb5b3b1f9b594e6fae5fae4"& ...

Learn how to redirect pages or app folders to a subdomain using Next.js

I have been extensively searching the internet for information on this topic, but I haven't come across any relevant articles. For example, in the root of my project, there's a folder called pages with the following file structure: | 404.js ...

Interested in creating a weather application that changes color based on the time of day

My attempt to create a weather app with a glowing effect has hit a roadblock. I want the app to glow "yellow" between 6 and 16 hours, and "purple" outside of those hours. I have assigned classes for AM and PM elements in HTML, and styled them accordingly i ...

What is the best way to use jQuery to attach functions to every input element?

Imagine you have a set of HTML markup and CSS like this: #CSS .inputhelp_text { background: #000; color: #fff; } .nodisplay { display: none; } <input class="inputhelp" id="firstname" /><span class="inputhelp_text nodisplay" id="help_firstname"& ...

The error message "node-soap - callback is not a function" is indicating that there

Encountering a common TypeScript error while calling a SOAP method on a node-soap client in NodeJS. Seeking guidance on resolving this issue. https://www.npmjs.com/package/soap - version: 0.35.0 Sample Code Snippet const [result] = await mySoapClient.Per ...

Retrieve the value of EJS depending on the JavaScript variable

I am in the process of developing a website for booking appointments using Express, EJS, and MongoDB. When a request is made to '/booking', the book page appears displaying all details about the doctor. Upon clicking the book button next to each ...

What is the procedure for defining the secret code for a private key in saml2-js?

I need to implement a key/cert with a passphrase in my project that's currently using saml2-js. I have already set up everything but encountering a bad decrypt error without the passphrase. Is there a way to incorporate this passphrase? Below are the ...

Access the contents of objects during the creation process

I am currently in the process of creating a large object that includes API path variables. The challenge I am facing is the need to frequently modify these API paths for application migration purposes. To address this, I had the idea of consolidating base ...

Creating a double-layered donut chart with Chart.js

I'm attempting to create a unique pie chart that illustrates an array of countries on the first level and their respective cities on the second level. After modifying the data in a JSON file to align with my goal, it doesn't seem to be working a ...

Utilizing Express JS to keep users on the same page upon submitting a form

Although this may seem like a simple query with available tutorials, I am struggling to locate the specific information. I utilized express-generator to create an app and included a basic form in a route. views/form.ejs <div> <h1>This is < ...

Align the Vuetify v-btn to the right in a horizontal layout

I'm having trouble aligning a v-btn to the right side. Despite trying various options, I can't seem to get it to work. I just want to know the simplest way to ensure that the register button is positioned at the very right of the column. For the ...

Is there a way to implement the border-box property for Internet Explorer versions 6 and

Similar Question: How to implement box-sizing in IE7 Anyone know a method or workaround to apply box-sizing:border-box; in IE6 and IE7? Even just for IE7? ...

Troubleshooting: jQuery click event not functioning correctly with if-else statement

For some reason, I can't seem to figure out how to toggle the color of all list items with a class of "link" between blue and black. I've searched through numerous posts but still can't find a solution. Working Example: http://jsfiddle.net/ ...

What is an alternative way to display static images in Rails 5 without relying on the Asset Pipeline?

I developed a web-based application with the backend built on Rails 5. Utilizing AngularJS for the frontend, I opted to not use the Asset Pipeline to deliver static content. Instead, I loaded all my scripts (JS & CSS) in the index.html file located within ...

What is the best way to align an element on the right side of the screen?

I am having some trouble positioning a CSS element to the right side of the header. I attempted using the following code: position: Absolute; top: 20px; right 0px; This method works, however, when adjusting the browser window, the text also moves. I ha ...