I'm facing a situation where I need to apply ng-style (or ng-class) multiple times depending on a variable.
However, this repetitive task of writing ng-class for the same functionality for each widget is quite cumbersome for me.
Is there a way to simplify this process? I am aware that creating a custom directive could help achieve this, but my attempts so far have not been successful.
Below is an excerpt from my code:
<div class="panel panel-primary" ng-style="expanded1 ? {{'height': viewPortHeight} : ''" ng-click="expanded1=!expanded1">Panel 1</div>
..........
<div class="panel panel-primary" ng-style="expanded2 ? {{'height': viewPortHeight} : ''" ng-click="expanded2=!expanded2">Panel 2</div>
Is it possible to create a directive (C or A) that can detect the "expanded" variable for each specific element and apply the style accordingly?
I attempted to do this, but encountered difficulties.
== Custom Directive
(function (app) {
app.directive('expandWidget', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
scope.$watch('expanded', function(expanded){
if(expanded)
element.css('height', 'viewPortHeight')
else element.css('height', '300px')
})
}
}
})
})
<div class="panel panel-primary" expand-widget ng-click="expanded1=!expanded1">Panel 1</div>
I am open to exploring alternative approaches that can achieve the same goal as mentioned above.