Search code examples
cssangularjsng-class

Using angular, how can I change a div's background image to match my user object's profileImage property?


Once my user logs in to my site, a user object is successfully getting attached to my controller's scope as $scope.user that looks a bit like this (simplified for clarity):

{
username: user2016
  , email: "user@user.com"
  , password: "hashedpasswordhere"
  , name: "A. User"
  , profileImage: "http://www.userpic.com"
}

Here is the related css:

.pic {
  height: 2.5em;
  width: 2.5em;
  border-radius: 100%;
  background-image: url("http://www.userpic.com");
  background-repeat: no-repeat;
  background-position: center;
  background-size: 100%;
  display: inline-block;
}

I want the currently logged in user to have their previously selected profile pic displayed in the top right when they are logged in, and I want to use angularJS to accomplish this. Obviously in the above CSS I have just manually plugged in the correct url, but if a different user logs in, I'm out of luck. After reading the ngClass docs I am still confused. Is there another directive I should be using?


Solution

  • Use ngStyle directive to set background-image:

    <div class="pic" ng-style="{'background-image': 'url(' + user.profileImage + ')'}"></div>