简体   繁体   中英

AngularJS changing class without ng-class

I'm looking to enable users to change the class from incomplete to complete on button click when function(response) returns 1. I have tried using issues, however; It doesn't work well as the HTML elements are loaded with a PHP loop so an ng-class expression doesn't work. This is because an if statement is run checking if it is incomplete or complete while the AngularJS expression wouldn't be able to check the database in this sense.

I added the 'active' variable, but I cant seem to put this into play without ng-class. Is there an alternative to jQuery's class add/remove? Or can someone think of another solution.

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 do I place here? } }, function(response) { }); }; }); 

You do not have to use ng-class - you can use regular class and put a parameter in it with {{}}. Then just change the variable in the $scope, and it will automatically adapt its behaviour.

Here is an 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 the controller code (it's ugly, but you'll get the point):

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";
    }
}

(Of course, classes are trivial):

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

This works just fine for me. I have not tested it out in an environment where the body of the page is generated by PHP, but should not make a difference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM