Web Developer @Paintzen, Former Product Manager @Offerpop, Entrepreneur, Crossfitter


Interpreting Angular Expressions inside of <style> tags

I'm currently rewriting parts of a site to render HTML using Angular on the front-end rather than rendering the HTML server-side using .jade templates. One of the issues I ran into was that my .jade files used data-binding to render dynamic CSS. So, for example:

        background: #{page.primary.color};

Since different pages can have different primary colors, this allows me to dynamically set the appropriate color for the appropriate page. Angular, however, doesn't support expressions inside of <style> tags natively, so I ended up finding & tweaking this nifty little script to do what I wanted:

angular.module('app').directive('parseStyle', [$interpolate, function($interpolate) {
    return function(scope, elem) {
        var exp = $interpolate(elem.html()),
            watchFunc = function() {return exp(scope);}

        scope.$watch(watchFunc, function(html) {

This is a directive that you can add as an attribute directly on the <style> tag, and it will interpolate the elements within the style tag, taking into account any of Angular's data binding. Then it sets a $watch on that html so that updates to the $scope will be taken into account. So now, something like this will work:

<style parse-style>
        background: {{page.primary.color}};
View Comments