[英]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没有显示,而是图像的url已更改为“localhost:”
Inspect元素显示了这一点,
<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指令在属性上设置了watch / watchcollection 。 当绑定的ng-style对象的键/值的值具有插值并且该值是动态绑定时,这会导致问题,因为ngstyle指令将在attr.ngStyle
上设置监视,即{'background-image' : 'url()'}
因为在ngstyle指令之前插入了插值。 因此,手表将不会第二次执行设置样式(即使ng-style指令的值将在视图上正确显示插值),以及最初设置的element.css({'background-image' : 'url()'})
样式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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.