Reputation: 2196
I'm using a directive at 3 places(A
, B
, C
) in the same page.
When I click on one of these(i.e. B
), it is adding a class(active) on it.
But meanwhile, I need to remove active class from another two buttons.
<test defaultclass="active">A</test>
<test>B</test>
<test>C</test>
app.directive("test", function() {
return {
restrict: 'E',
scope: {
defaultclass: "=?"
},
transclude: true,
link: function(scope, element, attrs) {
scope.activeclass = attrs.defaultclass
element.bind('click', function() {
scope.$apply(function() {
scope.activeclass = 'active';
});
});
},
template: '<btn ng-class="activeclass">Button <span ng-transclude></span></btn>'
}
});
Here is sample plunker: https://plnkr.co/edit/J330f4jrHZnpUS9J66qY?p=preview
In sort, I want to keep active only one button at a time.
Upvotes: 0
Views: 101
Reputation: 7208
A better way to do this would be to handle the click outside like this
<body>
<test is-active='chosen_button=="a"' ng-click='chosen_button="a"'>A</test>
<test is-active='chosen_button=="b"' ng-click='chosen_button="b"'>B</test>
<test is-active='chosen_button=="c"' ng-click='chosen_button="c"'>C</test>
</body>
and the directive
app.directive("test", function() {
return {
restrict: 'E',
scope: {
isActive: "="
},
transclude: true,
link: function(scope, element, attrs) {
},
template: '<btn ng-class="isActive?\'active\':\'\'">Button <span ng-transclude></span></btn>'
}
});
Upvotes: 1
Reputation: 780
There is two way to manage this things
**Way 1 ** (its easy)
you can add following line to fix this issue.
scope.$apply(function() {
angular.element('.active').removeClass('.active');// this is jLite code if in your project jquery so you can replace it with jquery code
scope.activeclass = 'active';
});
Way 2 (bit complex).
keep track each directive with unique id check when user is client
Upvotes: 1