简体   繁体   中英

How to make AngularJS directive as active

I'm using a directive at 3 places( A , B , C ) in the same page.
When I click on one of these(ie 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.

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

A better way to do this would be to handle the click outside like this

Working Plunkr

<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>'
  }
});

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