NG style with interpolated value not displaying background image?

I am trying to change the background image of a div using angular ng-style.

Here is my code.

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

However, when I run the project, the image is not displayed, instead the image URL changed to "localhost:"

The inspect element shows this,

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

Why is this? How can i fix this? Thanks

+4
source share
1 answer

I believe that ng-styleit will not work if the key value of the object expression contains interpolation and when they are connected asynchronously. Instead, you may need to bind the style object itself.

Example: -

  $scope.data.style = {'background-image' : 'url(/path/to/image)'}

and

  <div class="cover-image" ng-style="data.style"></div>

, :

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

, ngstyle watch/watchcollection . , / 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>
Hide result
+12

Source: https://habr.com/ru/post/1568661/


All Articles