Switching styles in AngularJS without using ng-class

My goal is to allow users to switch the class from incomplete to complete when they click a button and the function(response) returns 1. I have attempted to use ng-class, but it is not effective because the HTML elements are generated with a PHP loop. This means that an AngularJS expression cannot properly check the database to determine if the task is incomplete or complete.

I introduced the 'active' variable, but I am struggling to implement it without ng-class. Is there a different approach to adding or removing classes in jQuery? Or perhaps there is another solution that someone can suggest.

HTML:

<div class='task col-md-4 incomplete'>
    <button data-ng-click='toggleTask(".$lesson_id.", 0)' class='btn btn-default'>Mark as complete</b></button>
   </div>
   

AngularJS:

var app = angular.module('training-center', []);
            app.controller('task-manager', function(\$scope, \$http) {
               \$scope.toggleTask = function(id, active) {
                  \$scope.id = id;
                  \$http.post('app/modules/Controller.php?action=toggleTask', {
                     task_id: id,
                     active: active
                  }).
                  then(function(response) {
                        if (response.data == '1') {
                           //What should go here?
                        }
                     },
                     function(response) {

                     });
               };
            });
         

Answer №1

Instead of using ng-class, you can utilize a regular class and include a parameter in it using {{}}. Simply update the variable in the $scope, and it will adjust its behavior automatically.

Check out this example:

<div ng-app>
<div ng-controller="testCtrl">
    <div id="test" class="{{className}}">
        {{className}}
    </div>
    <a href="#" ng-click="increase();">Click</a>
</div>
</div>

And here is the code for the controller (it may not be the best looking, but it gets the job done):

function testCtrl($scope) {
    $scope.className = "red";

    $scope.increase = function() {
        if($scope.className == "red")
            $scope.className = "blue";
        else if($scope.className == "blue")
            $scope.className = "green";
        else if($scope.className == "green")
            $scope.className = "red";
    }
}

(The classes used are just examples):

.red {    color: #FF0000; }
.blue {    color: #0000FF;}
.green {    color: #00FF00;}

This method works well for me. Although I have not tried it in a PHP-generated page environment, it should work without any issues.

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

Establishing standard emit actions in a Vue JS component layout

I am dealing with a complex situation involving two nested Vue JS components. The child component is emitting certain events to the parent function, which I have defined within the parent component declaration. The issue here is that these events are being ...

The uiGridConstants are mysteriously missing from the global scope, even though they are clearly provided to

Are you struggling to aggregate values from a column in uigrid? I have injected uiGridConstants into the controller, and added ui.grid in my app.js file. Despite my efforts, uiGridConstants is constantly returning as undefined. Any solutions? GridOptions ...

Retrieve information from json, divide it, and transfer it to the chart for display

Greetings everyone! In my project, I am parsing a JSON file from an online API. However, I have encountered a roadblock while trying to split the data. Despite searching extensively on platforms like YouTube, I haven't been able to find a solution tha ...

Is using an interval the best method to ensure that an Ajax call has finished successfully?

I have a scenario with two input text fields and a save button. <input type="text" id="myInput" /> <input type="text" id="searchResult"/> <button id="myButton>save</button> The myInput t ...

Do Material-UI pickers only validate on blur, not on change events?

When you type inside the DatePicker component, validation is triggered immediately. Is there a way to trigger validation on blur instead of onChange when using @material-ui/pickers with material-ui v4 Passing the value to the blur function should work a ...

Choose the list item by identifying the corresponding unordered list

Is there a way to target the second li element within an ul list like this: HTML <ul> <li></li> <ul> <li>This one is what I need to select</li> </ul> </ul> ...

Encountering issues while trying to establish a connection to MongoDB through JavaScript

I have developed a code for seamlessly integrating various social networking logins with nodejs. Below is my server.js file: // include the necessary tools var express = require('express'); var app = express(); var port = process.env ...

Tips for traversing through jquery ui accordion when a single panel has been disabled

I currently have a jQuery UI accordion set up with Next and Previous buttons in each panel to navigate through the sections. Additionally, I have a select HTML element in one of the panels where I can choose an option. If Option 1 is selected, the second a ...

Transform HTML into a Vue component dynamically during runtime

Currently, I am in the process of learning Vue and working on a simple wiki page project. The raw article data is stored in a JSON file written using custom markup. For example, the following markup: The ''sun'' is {r=black black} shoul ...

Real-time filtering in personalized dropdown menu with search input

I have been attempting to create a custom list filter for input using a computed property. In one file, I am developing a widget, while in another file, I am implementing it. Below is the code snippet from the widget creation file: <template> ...

vaadin-grid selection issue not functioning

I'm encountering an issue with the row selection feature. The selectedItems array only updates when I select all items at once. I'm not sure if I'm missing something or if this is a bug. selectedItems: An array that contains the selected ...

Exploring the depths of npm in the realm of frontend development

Currently, I am delving into the realm of Javascript/Node development through self-teaching. While I grasp the concept of npm handling package installations for my Node application on the server side, I am struggling to comprehend how npm assists me with ...

Angular: displaying dates in a specific format while disregarding time zones

Is there a way to format date-time in Angular using DatePipe.format() without converting timezones, regardless of location? For instance, for various examples worldwide (ignoring time differences) I would like to obtain 07/06/2022: console.log('2022-0 ...

Developing cross-platform code using AngularJS

Our tech stack includes Angular with Bower and a Python API. We operate in multiple environments such as dev, staging, and prod. Currently, we manually adjust connection strings on the front-end after deploying fresh code to match the specific environment. ...

Angular unit test involving multiple directives [...] requesting a new/isolated scope for testing

When running a unit test, I encountered the following error: Error: [$compile:multidir] Multiple directives [sendEmail, sendEmail] asking for new/isolated scope on: <send-email resolve=""> The setup of my unit test involves compiling the component ...

javascript the unseen element becomes visible upon page loading

my website has the following HTML snippet: function getURLParameters() { var parameters = {}; var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { parameters[key] = value; }); return param ...

Challenge involving CSS and Javascript for solving puzzles

In my attempt to create a puzzle with 2 rows and 3 columns using CSS and JavaScript, I envision the pieces of the puzzle being black and cut into various shapes. The objective is for users to drag these pieces onto the board in order to complete it. I have ...

A ReferenceError was thrown because angular is not defined within the angular-moment.js script

After spending an hour trying to figure out what went wrong, I still can't solve this problem. I've searched on stackoverflow for answers, but nothing seems to be helpful. The issue arises when trying to integrate Moment js into my project. Che ...

Searching for a solution on how to retrieve data server-side in the newest version of Next.js? Attempted to use getStaticProps but encountering issues with it not executing

Currently tackling a project involving Django Rest Framework with Next.js, and encountering a roadblock while trying to fetch data from the API. Data is present at the following URL: http://127.0.0.1:8000/api/campaigns, visible when accessed directly. The ...

Having trouble with ESLint in VSCode? The ESLint extension seems to be ignoring linting rules after starting a new project within VSCode

I recently started using the ESLint extension in my VSCode editor for my React project. After creating the starter files, I ran the following command in my terminal: eslint --init This allowed me to choose the AirBnb style guide with React, which generat ...