Reputation: 2462
I'm quite fresh with Angular, so sorry if my question looks trivial
I have few buttons, I create by ng-repeat. They have some bootstrap classes to make them nice, but if button is "active" gets additional class - active. The problem is only one button can be active, and I have 2 separate groups (containers with different class name) of buttons on page. They should work the same, but clicking on button on one groups should not affect the buttons in other group.
Could you, please help me write a directive, which will bind click event to button and remove 'active' class from all buttons in group and add it to clicked button only?
EDITED: Here is a code in 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
}
];
}
]);
For fiddle I just changed markup (removed html and head tag and added ng-app to div (it was in html)) but somehow in fiddle it throws an error.
I also added class, but it doesn't work also...
Upvotes: 0
Views: 1290
Reputation: 111
You can use ng-class together with a variable in the model, like in this fiddle: https://jsfiddle.net/L5wm11s2/1/
Notice that I had to put the variables in the controller, not in the scope, and use the controller as
to be able to access the variables from the view. That's because ng-repeat creates a child scope for each repeated element - a copy of the original scope, but separated from it. Because of that, if I did simply selectedTan = tan
in ng-click, I'd end up setting the variable in the child scope. That means each button might consider itself selected, because it would have it's own selectedTan
variable.
Upvotes: 1