Ilya Ilin Ilya Ilin - 4 months ago 112
AngularJS Question

DOM manipulation in AngularJS 1.5 component

I tried to wrap my head around concept of AngularJS component and I kinda started to understand the principle, but when I tried to practice it, I found an example when I'm not sure how to implement it with a component.

I need to implement linear progressbar, it has a template, so logically must be a component, not a directive, but I can't find a way to do DOM manipulations in component and it seems weird to have a directive inside such a little component. Here is the basic implementation with directive:


angular.module('test', [])

.controller('MainCtrl', function($q, $scope) {

$scope.curVal= 0;

$scope.maxVal = 100;


.directive('progressBar', [function () {

return {
restrict: 'E',
scope: {
curVal: '@',
maxVal: '@'
template: "<div class='progress-bar'>"+
"<div class='progress-bar-bar'>testing</div>"+

link: function ($scope, element, attrs) {

function updateProgress() {
var progress = 0;

if ($scope.maxVal) {
progress = Math.min($scope.curVal, $scope.maxVal) / $scope.maxVal * element.find('.progress-bar').width();

element.find('.progress-bar-bar').css('width', progress);

$scope.$watch('curVal', updateProgress);
$scope.$watch('maxVal', updateProgress);


<progress-bar cur-val='{{curVal}}' max-val='{{maxVal}}'>


.progress-bar {
width: 120px;
height: 18px;
border-style: solid;
border-width: 1px;
background-color: rgba(100,50,100,.60);
border-color: #aaa;

.progress-bar-bar {
width: 0px;
background-color: rgb(100,50,100);
height: 100%;
color: #fff;
font-weight: normal

So, maybe I understood the principle of a component wrong, but I really googled a lot about it and thought that I understood the principle before I faced this example.

So my question is: Can I manipulate DOM in component in any way and if the answer is no, what is the way to implement this directive in component (and is it suitable at all)? I don't feel that adding directive to component just to change some CSS is an appropriate choice, so I'm stuck.


According to Angular's documentation, any DOM manipulation SHOULD be done using directives. It might be a big work now, but you can always reuse the directive within your project.

"At a high level, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element (e.g. via event listeners), or even to transform the DOM element and its children."

here's is how you will change the css using the directive

app.directive('changeStyle', function () {
return {
    restrict: 'AC',
    link: function (scope, element, attrs) {          
       scope.$watch(attrs.myAttr, function (value) {     
         element.css('background-color', (value ? 'transparent' : attrs.myBgcolor));