How to Set Background image of div with ng-style

前端 未结 3 1554
离开以前
离开以前 2020-12-02 20:30

Basically i have a link, and when it\'s clicked, i display a modal. Now i can display other properties on the modal like title except the background Image ! urghhh !

相关标签:
3条回答
  • 2020-12-02 20:51

    You have made some mistakes using single quotes, you have to take your variable outside the single quotes.

    For this div

    <div class="modalContainer" ng-style="{'background-image':'url({{selectedMeal.url}})'}">
    

    This part is being treated as a string

    'url({{selectedMeal.url}})'
    

    Whereas you would want angular to parse this variable

    {{selectedMeal.url}}
    

    So to solve this, the correct syntax is

    <div class="modalContainer" 
      ng-style="{'background-image': 'url(' + selectedMeal.url + ')'}">
    
    0 讨论(0)
  • 2020-12-02 20:56

    This is work for me. If you are retrieve data from json or any other try this

    <div class="your-class" [style.background-image]="'url(' + url.image + ')'" [ngStyle]="{  'background-size': 'cover','background-repeat': 'no-repeat'} ">
    
    0 讨论(0)
  • 2020-12-02 21:09

    Correct syntax for background-image is:

    background-image: url("src");
    

    Correct syntax for ng-style is:

     <div ng-style="{'background-image':'url({{re.url}})'}" ></div>
    

    for example :

    <div ng-repeat="re in recipes">
    <div ng-style="{'background-image':'url({{re.url}})'}" style="height: 100px"></div>
    </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/

    Update :

    <div ng-style="'{{re.url}}' != '' && {'background-image':'url({{re.url}})'}" style="height: 100px"></div>
    

    which would not attempt to fetch a non-existing image.

    0 讨论(0)
提交回复
热议问题