【发布时间】:2026-02-01 20:00:02
【问题描述】:
我对 Angular 很陌生,如果我的问题看起来微不足道,我很抱歉
我的按钮很少,由 ng-repeat 创建。他们有一些引导类来使它们变得更好,但是如果按钮是“活动的”,则会获得额外的类 - 活动。问题是只有一个按钮可以处于活动状态,并且我在页面上有 2 个单独的按钮组(具有不同类名的容器)。它们应该工作相同,但单击一组上的按钮不应影响另一组中的按钮。
你能帮我写一个指令,它将点击事件绑定到按钮,并从组中的所有按钮中删除“活动”类,并将其添加到点击按钮吗?
编辑: 这是jsfiddle中的代码https://jsfiddle.net/996o7nk1/1/
HTML:
<!doctype html>
<html ng-app="confApp">
<head>
<title>Test</title>
<style>
.active {color: red;}
</style>
</head>
<body>
<div ng-controller="ProjectConfCtrl">
<div class="tans">
<button class="btn btn-default btn-cph" ng-repeat="tan in tans" ng-class="active: tan.active === true" data-tan-type-id="{{tan.id}}">{{tan.name}}</button>
</div>
<div class="langs">
<button class="btn btn-default btn-cph" data-ng-repeat="lang in langs">{{ lang.name }}</button>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="custom.js"></script>
</body>
</html>
JavaScript:
var app = angular.module("confApp", []);
app.controller('ProjectConfCtrl', [
'$scope', function($scope) {
$scope.tans = [
{
id: 1,
name: 'Auto',
active: true
}, {
id: 2,
name: 'Import',
active: false
}
];
$scope.langs = [
{
id: 1,
name: 'English',
active: true
}, {
id: 2,
name: 'Spanish',
active: false
}, {
id: 3,
name: 'German',
active: false
}
];
}
]);
对于小提琴,我只是更改了标记(删除了 html 和 head 标签并将 ng-app 添加到 div(它在 html 中))但不知何故在小提琴中它会引发错误。
我也添加了类,但它也不起作用......
【问题讨论】:
-
即使它不能完全工作,如果你能向我们展示你到目前为止编写的代码将会很有用