如何在AngularJS

时间:2016-09-12 08:56:30

标签: html css angularjs ng-style

现在我将背景图片网址硬编码到CSS中。我想在AngularJS中使用逻辑动态选择背景图像。这是我现在拥有的:

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

如您所见,CSS中的背景图像引用了特定的文件位置。我希望能够以编程方式确定图像URL的位置。我真的不知道从哪里开始。我不知道JQuery。谢谢。

4 个答案:

答案 0 :(得分:11)

您可以使用ng-style使用AngularJS动态更改CSS类属性。

希望这个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>

修改-1

您可以按照以下方式更改背景图片:网址。

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

答案 1 :(得分:1)

您可以使用ng-classdocumation。 如果您想在directive支票directive - attrattr中执行此操作。

答案 2 :(得分:0)

您可以直接使用[ngStyle]。这是一张地图,所以你可以直接解决其中一个元素:[ngStyle.CSS_PROPERTY_NAME]

例如:

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

此外,对于服务资产,Angular具有bypassSecurityTrustStyle效用函数,在动态提供资源时可以派上用场。

答案 3 :(得分:-1)

在文本框中输入大小,您可以看到框更改高度和宽度

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