AngularJS Ng-style



我正在尝试使用ng样式作为div。我尝试了各种方法,并在Google和Stackoverflow上进行了检查,但我无法使其工作。仅显示testInsideDiv文本。我检查了一下我是否猜到了',但我没有看到,我尝试了很多不同的东西。有人看到问题出在哪里了吗?

这是代码:

<div ng-style="{'width' : {{deviceWidth}}, 'height' : {{deviceHeight}}, 'background-image':{{imagePath}}, 'background-size' : {{deviceWidth}} {{deviceHeight}}, 'background-repeat':'no-repeat'" ng-click="addOnClick($event)">testInsideDiv
                </div>

在调试器中看起来是这样的:

 <div ng-style="{'width' : 569px, 'height' : 300px,
 'background-image':'url('http://scada.voco.si/Portals/0/Scadas/2/28/28.jpg')',
 'background-size' : 569px 300px}, 'background-repeat':'no-repeat'"
 ng-click="addOnClick($event)"
 class="disable-user-behavior">testInsideDiv
                 </div>

您不能使用双大括号:

<div ng-style="{'width': deviceWidth, 'height': deviceHeight}">...</div>

主要错误-您忘记了ng样式对象的右大括号

如果更容易的话,你可以使用camelCase,如果你在插值变量,一定要引用它们。然而,您可能不想要插值,而是想要绑定,因此通过更改范围变量,样式也会发生变化:

<div ng-style="{
    width : deviceWidth, 
    height : deviceHeight, 
    backgroundImage: imagePath, 
    backgroundSize: deviceWidth + ' ' + deviceHeight, 
    backgroundRepeat: 'no-repeat'
    }" ng-click="addOnClick($event)">testInsideDiv</div>

点击此处查看实际操作:

angular.module('app', [])
  .controller('Ctrl', function($scope) {
    $scope.deviceWidth = '460px';
    $scope.deviceHeight = '276px';
    $scope.imagePath = 'url(http://cdn2.business2community.com/wp-content/uploads/2014/12/Super-Mario-no-longer-the-007.jpg)';
  
    // changing scope properties will make the style change
    // because the values are not interpolated
    // as in your original code
    $scope.shrink = function() {
      $scope.deviceWidth = '230px';
      $scope.deviceHeight = '138px';
    }
  })
div {
  border: 1px solid black;
  transition: all .5s linear;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="Ctrl" ng-style="{
    width : deviceWidth, 
    height : deviceHeight, 
    backgroundImage: imagePath, 
    backgroundSize: deviceWidth + ' ' + deviceHeight, 
    backgroundRepeat: 'no-repeat'
    }" ng-click="shrink()">testInsideDiv Click to shrink</div>

最新更新