I'm trying to change a background image of a div using angular ng-style.
Here is my code.
<div class="cover-image" ng-style="{'background-image' : 'url({{data.image}})'}"></div>
However when I run the project the image is not shown instead the url of the image has changed to 'localhost:'
Inspect element shows this,
<div class="cover-image" ng-style="{'background-image' : 'url(<some image url>)'}" style="background-image: url(http://localhost:<port>/);"></div>
CSS
.cover-image
{
height:100px;
width:100%;
display: block;
}
Why is this? How can I fix this? Thanks
I believe ng-style
will not work when the object expression's key value contains interpolation and when they are bound asynchronously. Instead you may have to bind the style object itself.
Example:-
$scope.data.style = {'background-image' : 'url(/path/to/image)'}
and
<div class="cover-image" ng-style="data.style"></div>
Interestingly the following works too:
<div class="cover-image" ng-style="{'background-image' : 'url(' + data.image + ')'}">
This could be because ngstyle directive sets watch/watchcollection on the attribute. This is causing the issue when the value of the bound ng-style object's key/value has interpolation and that value is bound dynamically, because ngstyle directive will have set the watch on attr.ngStyle
which is {'background-image' : 'url()'}
because of the interpolation having kicked in prior to ngstyle directive. Hence the watch will not execute for the second time to set the style (even though ng-style directive's value will show the interpolation properly on the view), and the initially set style of element.css({'background-image' : 'url()'})
will render the style with the url as that of the current domain (Which browser does).
angular.module('app', []).controller('ctrl', function($scope, $timeout) {
$scope.data = {};
$timeout(function() {
$scope.data.image = 'http://placehold.it/50x50';
$scope.data.style = {
'background-image': 'url(http://placehold.it/50x50)'
}
}, 1000)
});
.cover-image {
height: 100px;
width: 100%;
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
Will not display
<div class="cover-image" ng-style="{'background-image' : 'url({{data.image}})'}"></div>
Will display with Object binding
<div class="cover-image" ng-style="data.style"></div>
Will display with string concat
<div class="cover-image" ng-style="{'background-image' : 'url(' + data.image + ')'}"></div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With