ng-style,内插值不渲染背景图像?

时间:2014-12-22 19:08:25

标签: javascript html css angularjs angularjs-directive

我尝试使用角度ng样式更改div的背景图像。

这是我的代码。

<div class="cover-image" ng-style="{'background-image' : 'url({{data.image}})'}"></div>

但是,当我运行项目时,图像的网址没有显示,而是图像的网址已更改为&#39; localhost:&#39;

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;
}

这是为什么?我怎样才能解决这个问题?感谢

1 个答案:

答案 0 :(得分:12)

我相信当对象表达式的键值包含插值以及它们是异步绑定时,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 directive sets watch/watchcollection属性。当绑定的ng风格对象的键/值的值具有插值并且该值是动态绑定时,这会导致问题,因为ngstyle指令会将监视设置为attr.ngStyle {{1因为在ngstyle指令之前插入了插值。因此,手表将不会第二次执行以设置样式(即使ng-style指令的值将在视图上正确显示插值),并且最初设置的{'background-image' : 'url()'}样式将呈现使用url的样式与当前域的样式(哪个浏览器的样式)。

&#13;
&#13;
element.css({'background-image' : 'url()'})
&#13;
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)

});
&#13;
.cover-image {
  height: 100px;
  width: 100%;
  display: block;
}
&#13;
&#13;
&#13;