Issue
I'm trying to set a div background-image via AngularJS $scope variable.
This is what I have:
$scope.destination1 = 'web/images/' + obj.FirstPerson + '.png';
Then in the markup, I have this:
<div style="background-image:url(destination1)" class="destination"></div>
I'm learning AngularJS at this time, so pardon if this looks dumb to those familiar with how AngularJS works. Can we do something like this?
Update
Following the first reply, I did the changes and now the div looks like this:
<div id="destination" ng-style="{'background-image':'url({{destination1}})'}" class="destination"></div>
That is translated to this in the browser: http://i.gyazo.com/e9e08f738d8ea52ed1ca5e0338692f65.png
As you can see the background-image property comes from nowhere with no value assigned, although the ng-class property is populated correctly. Any idea what's happening?
Solution
Correct syntax for ng-style is:
<div ng-style="{'background-image':'url({{re.url}})'}" ></div>
JSFiddle : http://jsfiddle.net/U3pVM/7194/
also You can use custom directive :
app.directive('backgroundImageDirective', function () {
return function (scope, element, attrs) {
element.css({
'background-image': 'url(' + attrs.backgroundImageDirective + ')',
'background-repeat': 'no-repeat',
});
};
});
for example :
<div ng-repeat="re in recipes">
<div background-image-directive="{{re.url}}" style="height: 100px"></div>
</div>
JSFiddle : http://jsfiddle.net/U3pVM/7193/
dont forget :
<div ng-style="'{{re.url}}' != '' && {'background-image':'url({{re.url}})'}" style="height: 100px"></div>
update :
<div ng-controller="UserController" ng-app="myApp">
<div ng-style="{'background-image':'url({{destination1}})'}" style="height: 100px"></div>
</div>
var app = angular.module('myApp', []);
app.controller("UserController", function ($scope) {
$scope.destination1="http://scalabilitysolved.com/content/images/2014/May/stackoverflow.png";
});
JSFiddle : http://jsfiddle.net/U3pVM/7927/
Answered By - Football-Is-My-Life
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.