【问题标题】:Angular ng-style is adding a style attribute that is then not kept in sync [duplicate]Angular ng-style 正在添加一个样式属性,然后不保持同步 [重复]
【发布时间】:2015-12-06 00:42:11
【问题描述】:

我的 Angular 网站从 Web API 后端获取数据,最初显示的是通用背景。但登录后,客户背景图片 url 被检索并用于我的 ng-style 属性中。

当页面最初加载时,还会出现一个不在源代码中的样式属性,它将背景指向默认图像。

但是登录后,即使 ng-style 现在显示正确的背景图片 url,style 属性仍然指向默认 url。

如果我手动刷新页面(Chrome 的开发者设置中没有缓存),样式属性会更新,客户背景也会正确显示。

发生了什么事?为什么 Angular 会添加样式属性,然后不保持同步?

源代码

<div class="background-div" ng-style="{'background-image': 'url({{user.profile.Customer.BackgroundImageUrl || '../images/bg.jpg'}})'}"></div>

初始页面加载

<div class="background-div" ng-style="{'background-image': 'url(../images/bg.jpg)'}" style="background-image: url(http://localhost:10223/images/bg.jpg);"></div>

登录后

<div class="background-div" ng-style="{'background-image': 'url(http://megacorp.com/images/vipcustomer.jpg)'}" style="background-image: url(http://localhost:10223/images/bg.jpg);"></div>

强制无缓存刷新后

<div class="background-div" ng-style="{'background-image': 'url(http://megacorp.com/images/vipcustomer.jpg)'}" style="background-image: url(http://megacorp.com/images/vipcustomer.jpg);"></div>

固定代码

  <div class="background-div"
       ng-style="{'background-image': 'url(' + (user.profile.Customer.BackgroundImageUrl || '../images/bg.jpg') + ')'}">
  </div>

重新打开:

恕我直言,这个问题是不同的 b/c 它停留在 html 中,没有进入 $digest 和脚本,并显示页面处于不同状态时的阶段。但我听从你的判断:)

【问题讨论】:

    标签: html css angularjs ng-style


    【解决方案1】:

    ng-style 中不应包含 {{}} 插值,您可以在其中使用直接作用域变量。

    标记

    <div class="background-div" 
       ng-style="{'background-image': 'url('+user.profile.Customer.BackgroundImageUrl || 
       '../images/bg.jpg'+')'}">
    </div>
    

    【讨论】:

    • 我必须在表达式周围加上括号,这样它才能在连接之前执行 OR。然后它起作用了。请参阅显示修复的我的编辑。谢谢!
    • @toddmo no 从不在ng-style中使用插值括号
    • 我的意思是我必须输入(),而不是{{}}。谢谢!
    • @toddmo 哦,我在上面理解错了..对不起,谢谢:)很高兴帮助你..:)
    猜你喜欢
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 2015-04-20
    • 2015-05-20
    • 2015-06-08
    • 2019-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多