1

So I've written a custom directive to change a user's profile picture when they upload a new one. It watches for a change to the photo url and supposedly sets the element's background image to the new one upon a change.

Everything is working UNTIL the element.css() calls. For some reason, it seems to just be skipping those.

    client.directive('myDirective', function(){
    return {
        scope: { profilePhoto: '=myDirective' },
        link: function(scope, element, attrs){
            scope.$watch("profilePhoto",function(newValue,oldValue) {
                console.log(newValue) //This logs the correct value
               var url = newValue;
             if (!url) url = "../img/profile_default.png"
             element.css({
                'background-image': 'url(' + url +')', //never updates
                'background-size': 'cover',
                'background-repeat': 'no-repeat'
             })
            })
        }
    }
});

What's going on?

EDIT: Note that the background-image IS set correctly the first time through the code, but when I step through in a debugger, it's as if it's not even executed when the $watch variable changes.

2
  • can you provide a working fiddle? Commented Aug 12, 2015 at 14:41
  • I created a punkr and everything works how it should. Commented Aug 14, 2015 at 8:56

2 Answers 2

1

I am assuming this css code is wrong. Try this (notice the url parameter):

element.css({
    'background-image': 'url("' + url +'")',
    'background-size': 'cover',
    'background-repeat': 'no-repeat'
    })
Sign up to request clarification or add additional context in comments.

1 Comment

No dice. Tried and same behavior.
0

Maybe you should try to set directly the style object properties :

var style = element.currentStyle || window.getComputedStyle(element);

style.backgroundImage  = 'url("' + url +'")';
style.backgroundSize   = 'cover';
style.backgroundRepeat = 'no-repeat';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.