18

I have a div element and need to apply pseudo elements such as before and after dynamically. I will be pushing data to css "content" element dynamically from my scope. How can I do that using angular?

Sample CSS

    .bar:before {
  content: 'dynamic before text';
    height: 20px;
    }
.bar:after {
  content: 'dynamic after text';
    height: 20px;
}

<div class="bar"></div>

3 Answers 3

61

You can use a custom data attribute for this to keep it flexible:

.bar::before,
.bar::after
{
  background-color: silver;
}

.bar::before
{
  content: attr(data-before-content)
}

.bar::after
{
  content: attr(data-after-content)
}
<div class="bar" data-before-content="Hello" data-after-content="There">I have content</div>
<div class="bar" data-before-content="Hello">I have content</div>
<div class="bar" data-after-content="Different">I have content</div>
<div class="bar">I have content only</div>

Sign up to request clarification or add additional context in comments.

2 Comments

Cool. makes sense. let me try that. thnx!
You don't know how many hours I just spent trying to do something super specific in Angular 6. This plus attribute binding saved my life.
7

You can use dynamic html-attributes for the content, like this: JSBin: http://jsbin.com/sepino/edit?html,css,js,output

<!DOCTYPE html>
<html ng-app="test">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
    <script language="JavaScript">
        angular.module('test',[]).controller('testController',function(){
            this.textbefore = 'left ';
            this.textafter = ' right';
        });
    </script>
    <style>
    .bar:before {
        content:  attr(data-textbefore);
        height: 20px;
    }
    .bar:after {
        content:  attr(data-textafter);
        height: 20px;
    }
    </style>
    <meta charset="utf-8">
    <title>JS Bin</title>
</head>
<body ng-controller="testController as myCtrl">
    <div class="bar" data-textbefore="{{myCtrl.textbefore}}" data-textafter="{{myCtrl.textafter}}">inside</div>
</body>
</html>

1 Comment

thnx. that will be helpful.
2

You can use attributes in the content field. I guess you could pull in what you need from that.

span:before {
   content: attr(data-content);
}

1 Comment

thnx! let me try that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.