How to change a CSS property dynamically in AngularJS

后端 未结 4 1708
北海茫月
北海茫月 2021-01-12 05:23

Right now I have a background image URL hard-coded into CSS. I\'d like to dynamically choose a background image using logic in AngularJS. Here is what I currently have:

相关标签:
4条回答
  • 2021-01-12 05:49

    enter the size in textbox you can see box changes height and width

    <!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>

    0 讨论(0)
  • 2021-01-12 05:53

    You can use [ngStyle] directly. It's a map, so you can directly address one of its elements like so: [ngStyle.CSS_PROPERTY_NAME]

    For example:

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

    Also, for serving assets, Angular has the bypassSecurityTrustStyle utility function that can come in handy when serving up assets dynamically.

    0 讨论(0)
  • 2021-01-12 05:59

    You can use ng-style to dynamically change a CSS class property using AngularJS.

    Hope this ng-style example will help you to understand the concept at least.

    More information for 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>

    Edit-1

    You can change the background-image: URL by following way.

    $scope.style = function(value) {
       return { 'background-image': 'url(' + value+')' };
    }
    
    0 讨论(0)
  • 2021-01-12 06:02

    You can use ng-class : documation. If you want to do it in your directive check directive - attr : attr.

    0 讨论(0)
提交回复
热议问题