ng 样式,具有内值不呈现背景图像

ng-style with interpolated value not rendering the background image?

本文关键字:背景 图像 样式 ng      更新时间:2023-09-26

我正在尝试使用角度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>