I have a list of colour names in my application.
let colours = {
mango: '#e59c09',
midnight: '#1476a0'
};
I want to extend the ngStyle directive to be able to understand my custom colour names. I'm doing this by decorating the ngStyle directive. However, I've hit an uphill battle on the decorator's compile function. I can access the elements' ngStyle attribute, but it comes up as a string (understandably). JSON.parse()
doesn't work on it as it isn't always a valid JSON string due to bind once etc...
I simply want to step-in, iterate over all style keys, and if it contains color
, I want to check for the value - and replace with hex if it is one of the above custom colour.
I can't seem to be able to access any ngStyle internal functions, and the source code is confusing and short; it seems to just set element CSS - where does the $parse do its job? for example, when ng-style="{color: ctrl.textColor}"
- there is nothing in ngStyle source code that is pulling the value of ctrl.textColour
. Am I looking at the wrong place?
Anyway, how do I access ng-style key values so that I can change custom colours to its hex codes please?
This is what I've got so far in my decorator:
$provide.decorator('ngStyleDirective', function($delegate) {
let directive = $delegate[0];
let link = directive.link;
directive.compile = function(element, attrs) {
// Expression here is a string property
let expression = attrs.ngStyle;
return function(scope, elem, attr) {
// How do I iterate over and update style values here?
// Run original function
link.apply(this, arguments);
}
}
return $delegate;
});
I tried using regex to pull out patterns etc. and inspect elements, but, it seems like the wrong way to approach the problem to me as I then have to manually update string and pass it on to base link function.
Here's a plnkr example.
IF there is a better way to do what I'm trying to do, please let me know.