Jolle Jolle - 2 months ago 7
AngularJS Question

Controlling multiple DOMS with Angular Directive?

I'm fairly new to angular and I want to create a directive looking like this in AngularJS:

enter image description here

My approach is to make a template with something like:

progress-bar.html

<div class="container">
<div class="progress-line"></div>
</div>
<div class="current"> 11min </div>
<div class="max"> 24min </div>


Then use css to make the graphics and some javascript in the link/compile function of the directive to move the markers ("11min" and "24min") to the right positions, because i don't know the width of the progress-bar beforehand.

Is this a bad approach? I've not found anybody else handling multiple DOMs in one directive.

For testing, I tried to make the container red, when clicked:

app.directive('progressBar', function($timeout) {
var linkFn = function(scope, element, attrs) {
element.on("click", function () {
element.childNodes[0].css("background-color", "red");
});
};

return {
restrict: 'EA',
scope:{},
templateUrl: 'templates/directives/progress-bar.html',
link: linkFn
};
});


But this doesn't work:

Uncaught TypeError: Cannot read property '0' of undefined

Answer

first of, don't edit the dom like that

element.childNodes[0].css("background-color", "red");

use ngStyle thats the angular way https://docs.angularjs.org/api/ng/directive/ngStyle

like so:

<div class="container" ng-style="myStyle" ng-click="clickHandler()">
   <div class="progress-line"></div>
</div>
<div class="current"> 11min </div>
<div class="max"> 24min </div>


app.directive('progressBar', function($timeout) {    
    var linkFn = function(scope, element, attrs) {
        scope.myStyle = {};
        scope.clickHandler = function() { scope.myStyle.background-color = 'red' }
    };

    return {
        restrict: 'EA',
        scope:{},
        templateUrl: 'templates/directives/progress-bar.html',
        link: linkFn
    };
});