You can use ng-style
to dynamically change a CSS class property using AngularJS.
See the code below or this plunk (http://plnkr.co/edit/n4NlIfgfXIiNHWu5oTzS?p=preview)
I've created an array of colours to be used by the ng-repeat
and change the background-color
of each item dynamically.
Note that although all the items have a class called original
with red background, that value is updated (override) with a new colour from the array.
So now you're probably thinking: "Cool! If I can change the class color property dynamically I should be able to do the same with any other property, like the content
one right ?!?"
The answer is "Yes & No".
It seems pseudo selectors like :after
and :before
are treated differently.
"Although they are rendered by browsers through CSS as if they were
like other real DOM elements, pseudo-elements themselves are not part
of the DOM, and thus you can't select and manipulate them directly
with AngularJS, jQuery (or any JavaScript APIs for that matter"
You can find a full explanation on this post: (https://stackoverflow.com/a/5041526/1310945)
Have said that, I believe you can probably manage to work around this, using this solution (https://stackoverflow.com/a/16507264/1310945).
I haven't tried yet - but I might do another time just for fun.
On a side note, maybe there's a better solution ( and more AngularJs style approach) for what you're trying to do using ng-class
.
Anyway hope this at least send you on the right direction. :)
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootswatch/3.0.0/united/bootstrap.min.css">
<style>
ul {
list-style-type: none;
color: #fff;
}
li {
padding: 10px;
text-align: center;
}
.original {
background-color: red;
}
</style>
<script>
var myApp = angular.module('myApp', []);
myApp.controller("myAppCtrl", ["$scope", function($scope) {
$scope.colors = ['#C1D786', '#BF3978', '#15A0C6', '#9A2BC3'];
$scope.style = function(value) {
return { "background-color": value };
}
}]);
</script>
</head>
<body>
<div ng-controller="myAppCtrl">
<div class="container">
<div class="row">
<div class="span12">
<ul>
<li ng-repeat="color in colors">
<h4 class="original" ng-style="style(color)"> {{ color }}</h5>
</li>
</ul>
</div>
</div>
</div>
</div>
</body>
</html>