rks*_*ksh 4 html javascript css angularjs angularjs-directive
我正在尝试使用角度ng样式更改div的背景图像.
这是我的代码.
<div class="cover-image" ng-style="{'background-image' : 'url({{data.image}})'}"></div>
Run Code Online (Sandbox Code Playgroud)
但是,当我运行项目时,图像的url没有显示,而是图像的url已更改为"localhost:"
Inspect元素显示了这一点,
<div class="cover-image" ng-style="{'background-image' : 'url(<some image url>)'}" style="background-image: url(http://localhost:<port>/);"></div>
Run Code Online (Sandbox Code Playgroud)
CSS
.cover-image
{
height:100px;
width:100%;
display: block;
}
Run Code Online (Sandbox Code Playgroud)
为什么是这样?我怎样才能解决这个问题?谢谢
PSL*_*PSL 13
我相信ng-style当对象表达式的键值包含插值以及它们是异步绑定时,它们将不起作用.相反,您可能必须绑定样式对象本身.
例:-
$scope.data.style = {'background-image' : 'url(/path/to/image)'}
Run Code Online (Sandbox Code Playgroud)
和
<div class="cover-image" ng-style="data.style"></div>
Run Code Online (Sandbox Code Playgroud)
有趣的是,以下也有效:
<div class="cover-image" ng-style="{'background-image' : 'url(' + data.image + ')'}">
Run Code Online (Sandbox Code Playgroud)
这可能是因为ngstyle指令在属性上设置了watch/watchcollection.当绑定的ng-style对象的键/值的值具有插值并且该值是动态绑定时,这会导致问题,因为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)
});Run Code Online (Sandbox Code Playgroud)
.cover-image {
height: 100px;
width: 100%;
display: block;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)