gpt4 book ai didi

javascript - AngularJS 在没有 ng-class 的情况下更改类

转载 作者:行者123 更新时间:2023-11-27 23:53:38 25 4
gpt4 key购买 nike

我希望用户能够在函数(响应)返回 1 时单击按钮将类从不完整更改为完整。但是,我尝试过使用问题;它不能很好地工作,因为 HTML 元素是通过 PHP 循环加载的,因此 ng-class 表达式不起作用。这是因为运行 if 语句来检查它是不完整还是完整,而 AngularJS 表达式无法在这种意义上检查数据库。

我添加了“active”变量,但如果没有 ng-class,我似乎无法将其发挥作用。有没有替代 jQuery 的类添加/删除的方法?或者有人能想到另一种解决方案。

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) {

});
};
});

最佳答案

您不必使用 ng-class - 您可以使用常规类并使用 {{}} 将参数放入其中。然后只需更改 $scope 中的变量,它就会自动调整其行为。

这是一个例子:

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

还有 Controller 代码(它很难看,但你会明白的):

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

(当然,类(class)是微不足道的):

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

这对我来说效果很好。我还没有在由 PHP 生成页面主体的环境中对其进行测试,但应该不会产生影响。

关于javascript - AngularJS 在没有 ng-class 的情况下更改类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32468841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com