How to change the class of a :after in Angularjs using ng-class?

Asked

Viewed 891 times

3

I have a div with an after and would like to change the background color of that after dynamically via controller, however I am not succeeding in importing ng-class in parent div.

<div class="infos" ng-class="myController.infoBlue">
   My Infos.
   :after
</div>

Note: I have different styles in div and :after. Div has a background of one color and my after has a background of another color and I want to change only the after.

2 answers

1

Take a look at the code below and see if it helps you.

Or see it working on http://plnkr.co/edit/zmokTDQnJsArl49ynczK?p=preview

<!doctype html>
    <html ng-app>
      <head>
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
<script>
    function Ctrl($scope) {
      $scope.items = [{'color' : 'blue'}, {'color':'red'}, {'color':'green'}];
      $scope.selection = $scope.items[0];
    }
</script>

        <style>

           p.blue::after { 
            content: " - in Blue";
            background-color:blue;
            color: #fff;
          }

          p.red::after { 
            content: " - in Red";
            background-color:red;
            color: #fff;
          }

          p.green::after { 
            content: " - in Green";
            background-color:green;
            color: #fff;
          }

        </style>
      </head>
      <body>

    <div ng-controller="Ctrl">
      <p ng-class="selection.color">I love Brazil! </p>

      <select ng-model="selection" ng-options="item.color for item in items">
      </select>
      <tt>selection={{selection.color}}</tt>
    </div>
      </body>
    </html>
  • Hello didn’t work for me. I have different styles between div and :after. div has a background of one color and my after has another. and I just want to change the after.

  • @peterq I changed the code again. I used only DIVS and the same way Voce spoke. The Parent div is yellow and the other Divs with the :after have independent colours. http://plnkr.co/edit/zmokTDQnJsArl49ynczK?p=preview

  • Hello is not the Parent is in the same div. bag? . div { background-color: blue &:after{background-color: Yellow}}

0

The ng-class works through a condition, it needs an expression to apply or not a certain class, for example:

<div class="minhaDiv" ng-class="{'classeSecundaria': meuValor > 5}">Teste</div>

In this case the class classeSecundaria would be applied to the div if the property meuValor has a value greater than 5.

In your case just do this check and apply the desired class. Otherwise it’s just configuration css.


To change the color dynamically, you can do something like this:

.menu:after {
  background:red;
}
.menu.azul:after {
  background:blue;
}

See this example working:

http://plnkr.co/edit/M5MtkqGSqxJRZC8t2C77?p=preview

Browser other questions tagged

You are not signed in. Login or sign up in order to post.