Search code examples
cssangularjsclassconditional-statementsng-class

How to add a class to an element when another element gets a class in angular?


I have a scrollspy directive that adds an ".active" class to a nav item. When the first nav item has the ".active" class I want my header bar to contain a certain class too. Attached is a simplified example, but how can I add ".active" to item 1 by only looking at the classes in item 2. jsfiddle

<div ng-app>
    <div ng-controller='ctrl'>
        <div id="item1" ng-class="if item2 has class=active then add active class here">Item 1</div>
        <div id="item2" ng-class="myVar">Item 2</div>
</div>

    //I can't use a scope object I can only look at item 2's classes
    <button type="button" ng-click="myVar='active'">Add Class</button>
    <button type="button" ng-click="myVar=''">Remove Class</button>

Solution

  • Click here for live demo.

    You'll need a directive to interact with the element. I would have the directive watch the element's classes and have it call a function from your controller when the classes change. Then, your controller function can apply the logic specific to your need, which is to set a flag letting another element know how to respond.

    angular.module('myApp', [])
    .controller('MyCtrl', function($scope) {
      $scope.foo = function(classes) {
        if (~classes.indexOf('active')) {
          $scope.otherItemIsActive = true;
        }
      };
    })
    .directive('onClassChange', function() {
      return {
        scope: {
          onClassChange: '='
        },
        link: function($scope, $element) {
          $scope.$watch(function() {
             return $element[0].className; 
          }, function(className) {
            $scope.onClassChange(className.split(' '));
          });
        }
      };
    })
    ;