I created a custom directive whose purpose is to dynamically assign a base64 string and file extension as a background image to a <div> which will be used as a user profile photo. Here is the relevant code:
app.directive('backImg', function() {
return {
link: function(scope, element, attrs) {
scope.$watchGroup(['profilePictureStr', 'profilePictureExt'],
function(newValues, oldValues, scope) {
element.css({
'background-image': 'url(data:image/' +
scope.profilePictureExt + ';base64,' +
scope.profilePictureStr + ')',
'background-size':'contain',
'background-repeat':'no-repeat',
'background-position':'center'
});
});
}
};
});
here is the <div> whose CSS I would like to dynamically control from the directive:
<div back-img>
What I currently observe is that the first time the watch gets called, upon load, the element.css() call succeeds. However, at page load the scope variables profilePictureStr and profilePictureExt have not yet been assigned, and are empty string. Shortly thereafter, the page makes a REST call to retrieve the base-64 image string corresponding to the logged in user. However, the second time the watch is called, the element.css() call does not appear to stick. The code does in fact get called, but the CSS seems to be unchanged.
Is it not possible to dynamically change CSS in the DOM from an Angular directive more than once? At this point I am leaning towards just putting everything into the style attribute of the <div> in question, but I would much rather use a directive to do this if possible.
$watchcallback to check that the two scope variables aren't''? Then the next timeelement.cssis called it will be with the correct values.