0

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

2 Answers 2

2

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
    };
});
Sign up to request clarification or add additional context in comments.

3 Comments

Okay, but how will I then get the width of the container?
why do you need the width of the container? just place the progress bar inside the container and calculate the percent
btw, you might want to look at bootstrap-ui angular-ui.github.io/bootstrap it is a really useful angularjs bootstarp library, which has progress line directives... but if you are dead set on creating your own it is fairly easy
1

.css isn't a native method over DOM, you can use that just by passing DOM to angular.element(jQLite).

element.children().eq(0).css("background-color", "red");

Alternative method would be you could use ng-style/ng-class directive which can do the same thing.

1 Comment

@charlietfl thank you for heads up, corrected mine answer :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.