How to add a style tag to the head using angularjs directive
-
02-01-2020 - |
Question
Hi I am allowing users to specify whether they want to print reports in a landscape or portrait format.
I was wondering if it's possible to add this (see below) into the head of the web document using a angularjs directive? That way it will change the printing size depending on the user input.
<style>@media print{@page {size: landscape}}</style>
Solution
This depends on whether you are going to be using this functionality in many different places. If you only need it once, then a directive may be overkill.
You can simply put
<style> @media print {@page { size: {{ orientation }} } }</style>
within your angular controller, and specify orientation on the $scope.
To my knowledge there is no need for the style tag to be in the head.
OTHER TIPS
You can use the ngStyle directive to conditionally apply css. See AngularJS ngStyle
. The example at the end of the link shows how to do that.
I had to crate custom stylesheet on the fly with unique IDs, I made it nicely work with angularJS like this :
<style type="text/css"
ng-bind="vm.css">
</style>
(note the use of ng-bind
)
where vm.css looks like that in the controller
vm.css = `#${$scope.id} { background-color: red; }`
Hope this helps!