Skip to content

Instantly share code, notes, and snippets.

@Megabytemb
Created September 3, 2015 02:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Megabytemb/89cff38a2dd18f87bb58 to your computer and use it in GitHub Desktop.
Save Megabytemb/89cff38a2dd18f87bb58 to your computer and use it in GitHub Desktop.
Using Angular Material theme colors on any element
var app = angular.module('DashboardApp', ['ngMaterial']);
var _theme;
app.config(function ( $mdThemingProvider) {
$mdThemingProvider
.theme('default')
.accentPalette('orange')
.dark();
_theme = $mdThemingProvider.theme();
});
app.directive('mdStyleColor', ['$mdColorPalette',
function ($mdColorPalette) {
return {
restrict: 'A',
scope: { mdStyleColor: '=' },
link: function (scope, element, attrs)
{
for (var p in scope.mdStyleColor)
{
if (scope.mdStyleColor.hasOwnProperty(p))
{
var themeColors = _theme.colors;
var split = (scope.mdStyleColor[p] || '').split('.');
if (split.length < 2) split.push('default');
var hueR = split[1] || 'default'; // 'hue-1'
var colorR = split[0] || 'primary'; // 'warn'
// Absolute color: 'orange'
var colorA = themeColors[colorR] ?
themeColors[colorR].name : colorR;
// Absolute Hue: '500'
var hueA =
themeColors[colorR] ?
themeColors[colorR].hues[hueR] || hueR :
hueR;
var colorValue = $mdColorPalette[colorA][hueA] ?
$mdColorPalette[colorA][hueA].value :
$mdColorPalette[colorA]['500'].value;
element.css(p, 'rgb(' + colorValue.join(',') + ')');
}
}
}
}
}]);
<h1 class="md-display-1" md-style-color="{'color': 'accent'}">hi</h1>
<h1 class="md-display-1" md-style-color="{'color': 'primary.hue-1'}">hi</h1>
<h1 class="md-display-1" md-style-color="{'color': 'warn.hue-3'}">hi</h1>
@JoachimR
Copy link

thanks, took me only 1 minute to put into my app!

@casey-sayre
Copy link

awesome, thanks! after a couple of weeks of bliss with your cool directive I messed with custom themes and seem to have hit a wall. using stock code from the theme generator (https://angular-md-color.com/#/), the defined custom palettes don't show up on the $mdColorPalette object and so the assignment of colorValue on line 43 leads to TypeError. FYI and thanks again for the code. I'll keep looking at it. btw I wonder about getting the theme at link time, have the theme name as an attribute, for the multiple theme scenario

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment