使用 angular,如何更改 div 的背景图像以匹配我的用户对象的 profileImage 属性?
Using angular, how can I change a div's background image to match my user object's profileImage property?
一旦我的用户登录到我的网站,一个用户对象就成功地附加到我的控制器的范围作为 $scope.user 看起来有点像这样(为清楚起见进行了简化):
{
username: user2016
, email: "user@user.com"
, password: "hashedpasswordhere"
, name: "A. User"
, profileImage: "http://www.userpic.com"
}
这是相关的 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;
}
我希望当前登录的用户在登录时在右上角显示他们之前选择的个人资料图片,我想使用 angularJS 来完成此操作。显然在上面的 CSS 中我只是手动插入了正确的 url,但是如果不同的用户登录,我就不走运了。阅读 ngClass 文档后,我仍然感到困惑。我应该使用其他指令吗?
使用ngStyle指令设置background-image
:
<div class="pic" ng-style="{'background-image': 'url(' + user.profileImage + ')'}"></div>
好吧,我不知道可以修复它的指令,至少不是开箱即用的指令。但是你可以这样做:
<div class='pic' style='background-image: url( "{{user.profileImage}}" );'></div>
您可以将占位符图像加载到 pic2
class 中,以便默认显示一个,并使用 angular 双向数据绑定来更改样式图片。
另一种选择是将 img
标记与 ng-src
angular 指令结合使用。
<img ng-src='{{user.profileImage}}'>
他是ng-src
指令的文档。
这个有效:
<div class="pic" ng-style="{'background-image': 'url({{user.profileImage}})'}"></div>
一旦我的用户登录到我的网站,一个用户对象就成功地附加到我的控制器的范围作为 $scope.user 看起来有点像这样(为清楚起见进行了简化):
{
username: user2016
, email: "user@user.com"
, password: "hashedpasswordhere"
, name: "A. User"
, profileImage: "http://www.userpic.com"
}
这是相关的 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;
}
我希望当前登录的用户在登录时在右上角显示他们之前选择的个人资料图片,我想使用 angularJS 来完成此操作。显然在上面的 CSS 中我只是手动插入了正确的 url,但是如果不同的用户登录,我就不走运了。阅读 ngClass 文档后,我仍然感到困惑。我应该使用其他指令吗?
使用ngStyle指令设置background-image
:
<div class="pic" ng-style="{'background-image': 'url(' + user.profileImage + ')'}"></div>
好吧,我不知道可以修复它的指令,至少不是开箱即用的指令。但是你可以这样做:
<div class='pic' style='background-image: url( "{{user.profileImage}}" );'></div>
您可以将占位符图像加载到 pic2
class 中,以便默认显示一个,并使用 angular 双向数据绑定来更改样式图片。
另一种选择是将 img
标记与 ng-src
angular 指令结合使用。
<img ng-src='{{user.profileImage}}'>
他是ng-src
指令的文档。
这个有效:
<div class="pic" ng-style="{'background-image': 'url({{user.profileImage}})'}"></div>