ng 样式,具有内值不呈现背景图像
ng-style with interpolated value not rendering the background image?
我正在尝试使用角度ng样式更改div的背景图像。
这是我的代码。
<div class="cover-image" ng-style="{'background-image' : 'url({{data.image}})'}"></div>
但是,当我运行项目时,图像没有显示,而是图像的 url 已更改为"localhost:"
检查元素显示了这一点,
<div class="cover-image" ng-style="{'background-image' : 'url(<some image url>)'}" style="background-image: url(http://localhost:<port>/);"></div>
.CSS
.cover-image
{
height:100px;
width:100%;
display: block;
}
这是为什么呢?我该如何解决这个问题?谢谢
我相信当对象表达式的键值包含插值并且它们异步绑定时ng-style
不起作用。相反,您可能必须绑定样式对象本身。
例:-
$scope.data.style = {'background-image' : 'url(/path/to/image)'}
和
<div class="cover-image" ng-style="data.style"></div>
有趣的是,以下方法也有效:
<div class="cover-image" ng-style="{'background-image' : 'url(' + data.image + ')'}">
这可能是因为 ngstyle 指令在属性上设置了监视/监视集合。当绑定的 ng 样式对象的键/值的值具有插值并且该值是动态绑定的时,这会导致问题,因为 ngstyle 指令会将监视设置为attr.ngStyle
,这是{'background-image' : 'url()'}
因为插值在 ngstyle 指令之前启动。因此,手表不会第二次执行来设置样式(即使 ng-style 指令的值将在视图上正确显示插值),并且初始设置的 element.css({'background-image' : 'url()'})
样式将使用 url 呈现为当前域的样式(哪个浏览器这样做)。
angular.module('app', []).controller('ctrl', function($scope, $timeout) {
$scope.data = {};
$timeout(function() {
$scope.data.image = 'http://placehold.it/50x50';
$scope.data.style = {
'background-image': 'url(http://placehold.it/50x50)'
}
}, 1000)
});
.cover-image {
height: 100px;
width: 100%;
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
Will not display
<div class="cover-image" ng-style="{'background-image' : 'url({{data.image}})'}"></div>
Will display with Object binding
<div class="cover-image" ng-style="data.style"></div>
Will display with string concat
<div class="cover-image" ng-style="{'background-image' : 'url(' + data.image + ')'}"></div>
</div>
相关文章:
- 可以在这里为背景图像设置滤镜吗
- 使用 js 将背景图像设置为 HTML
- 如何使用css动画/javascript使具有背景图像的元素出现
- 循环浏览多个身体背景图像
- 背景图像顶部的滚动图像不移动
- 在pdfmake中嵌入背景图像
- 修复选择菜单时的背景图像
- 使用css()设置背景图像;不起作用
- 鼠标悬停时如何居中放大背景图像
- 强制谷歌为javascript背景图像编制索引
- 淡入不带HTML的背景图像
- 具有淡入淡出效果的全背景图像
- 未加载随机背景图像
- 背景图像前显示Javascript警报
- javascript背景图像位置循环
- CSS动画背景图像的过渡越来越暗
- "Ken Burns效应”;悬停背景图像
- 通过ID JavaScript显示随机背景图像
- JavaScript背景图像
- 带有图像和背景图像的ClipTo