How to make an animated horizontal bar graph in Angular

By: Ryan Wong at

When I was looking for a simple animated two sided horizontal bar graph, I couldn’t find one on the internet so I made it.
How it works:
1.You pass in the left score, right score and the description of the score in the middle.
2.Then the CSS will expand the bars outward proportional to the value pass in.

For example if left score is 5 and right score is 10, then the left side will be half the width of the right side.

HTML:

1
2
<horizontalbargraph  leftscore="leftScore" rightscore="rightScore"
name="center_score"></horizontalbargraph>


Angular:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
var app = angular.module('home', [ 'ui-tpl'])
angular.module("ui-tpl", ["template/stat/horizontal-graph.html"])
.directive('horizontalbargraph', [horizontalbargraph])

function horizontalbargraph() {
return {
restrict: 'E',
templateUrl: 'template/stat/horizontal-graph.html',
scope: {
leftscore: '=',
name: '@',
rightscore: '='
},
link: function(scope) {
scope.leftBar = {
'max-width': ((scope.leftscore)/(scope.leftscore + scope.rightscore) * 100) + '%',
animation: "move 2s linear 0.1s 1",
'animation-fill-mode': "forwards"
};
scope.rightBar = {
'max-width': ((scope.rightscore)/(scope.leftscore + scope.rightscore) * 100) + '%',
animation: "move 2s linear 0.1s 1",
'animation-fill-mode': "forwards"
};
}
};
}

angular.module("template/stat/horizontal-graph.html", [])
.run(["$templateCache", function($templateCache) {
$templateCache.put("template/stat/horizontal-graph.html",
"<div class=\"horizontal-bar-graph\" ng-if=\"leftscore>0||rightscore>0\">\n" +
"<div class=\"bar-3\">\n" +
"<div class=\"bar-fill-left\" ng-style=\"leftBar\"><span ng-if=\"leftscore>0\">{{leftscore}}</span></div>\n" +
"</div>\n" +
"<div class=\"bar-2\">{{name}}</div>\n" +
"<div class=\"bar-3\">\n" +
" <div class=\"bar-fill-right\" ng-style=\"rightBar\"><span ng-if=\"rightscore>0\">{{rightscore}}</span></div>\n" +
"</div>\n" +
"<div class=\"clearfix\"></div>\n" +
"</div>");
}]);



CSS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
.horizontal-bar-graph{
margin: 10px 0;
}
.bar-3{
width: 40%;
float:left;
text-align: center;
}
.bar-2{
width: 20%;
float:left;
text-align: center;
}
.bar-fill-left{
height: 20px;
background-color: #5cb85c;
float:right;
text-align: center;
color:white;
animation: move 2s linear 1 forwards;
}

.bar-fill-right{
height: 20px;
background-color: #d9534f;
float:left;
text-align: center;
color:white;
animation: move 2s linear 1 forwards;
}

@keyframes move {
0% {
width:0%;
}
100% {
width: 100%;
}
}

hope this helps you out