How to change a CSS property dynamically in AngularJS

后端 未结 4 1758
北海茫月
北海茫月 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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;
    }
    
    
    
    • {{ color }}

    Edit-1

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

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

提交回复
热议问题