一尘不染

如何使用ng-style设置div的背景图像

angularjs

基本上,我有一个链接,当单击它时,我会显示一个模式。现在我可以在模态上显示其他属性,例如标题,除了背景图片!urg!

这是模态:

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

                <div id="modalHeader"> 
                <div style="padding-top: 10px;">{{selectedMeal.title}}</div>

                </div>
</div>

这些是链接:

<div ng-click='selectMeal(meal)' class="contentItem" ng-repeat='meal in recipes | filter:searchText' ng-style="{'background-image':'url({{ meal.url }})'}">
                    <span id="contentItemHeader">{{ meal.title }}</span>
                    <span id="contentItemLevel">{{ meal.level }}</span>
</div>

json:

recipes:[
    {
      "type": "Breakfast",
      "title": "Chili con carne",
      "description": "A spicy and fragrant chili with ground beef, kidney beans, tomatoes, onions and garlic. Best served over rice with a dollop of sour cream and some cheese on top.",
      "ratings": 4,
      "duration": 12,
      "level":"medium",
      "url":"http://31.media.tumblr.com/bc0ea7c5f95701bff499f78b59d23e68/tumblr_mr74z9Lt3O1rs0z5go1_500.jpg",
      "ingredients": 
          [
            {
              "vegetable": "40ml"
            }
          ],
      "method": 
          [
            {
              "1": "In a medium sized stock pot, heat the oil over  heat. Saute onions, chile peppers andgarlic until soft."
            }
          ]
    },

    {
      "type": "Breakfast",
      "title": "Spicy Noodle",
      "description": "A spicy and fragrant chili with ground beef, kidney beans, tomatoes, onions and garlic. Best served over rice with a dollop of sour cream and some cheese on top.",
      "ratings": 5,
      "duration": 30,
      "level":"hot",
      "url":"http://38.media.tumblr.com/875b5eeb5b1efa37d2e9d36fbad836d3/tumblr_mzczesVrZD1rimr6yo1_1280.jpg",
      "ingredients": 
          [
            {
              "vegetable": "40ml"
            }
          ],
      "method": 
          [
            {
              "1": "In a  sized stock pot, heat the oil over  heat. Saute onions, chile peppers andgarlic until soft."
            }
          ]
    }]

阅读 297

收藏
2020-07-04

共1个答案

一尘不染

使用单引号引起了一些错误,您必须将变量带到单引号之外。

对于这个div

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

这部分被视为字符串

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

而您希望angular解析此变量

{{selectedMeal.url}}

所以要解决这个问题,正确的语法是

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