How to change CSS property dynamically in Angular

Right now I have the url source code encoded in CSS. I would like to dynamically select a background image using logic in Angular. Here is what I have now:

HTML

<div class="offer-detail-image-div"><div>

CSS

.offer-detail-image-div {
  position: relative;
  display: block;
  overflow: hidden;
  max-width: 800px;
  min-height: 450px;
  min-width: 700px;
  margin-right: auto;
  margin-left: auto;
  padding-right: 25px;
  padding-left: 25px;
  -webkit-box-flex: 1;
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  border-radius: 5px;
  background-image: url('/assets/images/118k2d049mjbql83.jpg');
  background-position: 0px 0px;
  background-size: cover;
  background-repeat: no-repeat;
}

As you can see, the CSS background image refers to a specific file location. I want to be able to programmatically locate the image url. I really don't know where to start. I do not know jQuery. Thank.

+4
source share
4 answers

You can use the ng style to dynamically change the properties of a CSS class using the AngularJS function.

, ng .

ngStyle

var myApp = angular.module('myApp', []);
myApp.controller("myAppCtrl", ["$scope", function($scope) {
      $scope.colors = ['#C1D786', '#BF3978', '#15A0C6', '#9A2BC3'];
      $scope.style = function(value) {
          return { "background-color": value };
      }
}]);
ul{
  list-style-type: none;
  color: #fff;
}
li{
  padding: 10px;
  text-align: center;
}
.original{
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="myAppCtrl">
  <div class="container">
    <div class="row">
      <div class="span12">
        <ul>
          <li ng-repeat="color in colors">
            <h4 class="original" ng-style="style(color)"> {{ color }}</h4>
          </li>
        </ul>
      </div>
    </div>
  </div>
</div>
</body>
Hide result

Edit-1

background-image: url .

$scope.style = function(value) {
   return { 'background-image': 'url(' + value+')' };
}
+6

ng-class: documation. directive directive - attr: attr.

+1

[ngStyle]. , : [ngStyle.CSS_PROPERTY_NAME]

:

<div class="offer-detail-image-div"
     [ngStyle.background-image]="'url(' + backgroundSrc + ')'">Hello World!</div>

, Angular bypassSecurityTrustStyle, .

0

, ,

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<p>Change the value of the input field:</p>

<div ng-app="" >

<input  ng-model="myCol" type="textbox">

<div style="background-color:red; width:{{myCol}}px; height:{{myCol}}px;"> </div>


</div>


</body>
</html>
Hide result
-1

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


All Articles