Reputation: 1416
I'm fairly new to angular and I want to create a directive looking like this in AngularJS:
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
Upvotes: 0
Views: 54
Reputation: 136154
.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.
Upvotes: 1
Reputation: 2819
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
};
});
Upvotes: 2