Reputation: 799
I am trying to use ng-style for a div. I tried all sorts of things and checked about it on Google and Stackoverflow but I can't get it to work. Only testInsideDiv
text gets displayed. I check if I mised any '
but I don't see it and I have tried a lot of diffrent things. Anyone sees what the problem is?
Here is the code:
<div ng-style="{'width' : {{deviceWidth}}, 'height' : {{deviceHeight}}, 'background-image':{{imagePath}}, 'background-size' : {{deviceWidth}} {{deviceHeight}}, 'background-repeat':'no-repeat'" ng-click="addOnClick($event)">testInsideDiv
</div>
And it looks like this in debuger:
<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>
Upvotes: 0
Views: 1345
Reputation: 37701
Main error - you forgot the closing curly brace of the ng-style object.
You use camelCase if it's easier for you, and if you're interpolating variables, make sure you quote them. However, you probably don't want interpolation, but binding, so by changing scope variables, the style will also change:
<div ng-style="{
width : deviceWidth,
height : deviceHeight,
backgroundImage: imagePath,
backgroundSize: deviceWidth + ' ' + deviceHeight,
backgroundRepeat: 'no-repeat'
}" ng-click="addOnClick($event)">testInsideDiv</div>
See it in action here:
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>
Upvotes: 1
Reputation: 1266
You must not use the double braces:
<div ng-style="{'width': deviceWidth, 'height': deviceHeight}">...</div>
Upvotes: 2