AngularJS - ng-style 不更新 css 背景属性 [英] AngularJS - ng-style does not update css background property

查看:36
本文介绍了AngularJS - ng-style 不更新 css 背景属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回图像 URL 的服务,它使用以下代码调用:

I have a service that returns image URL, and it is called using the following code:

angular.forEach(results, function (item) {
     item.img = "/images/searchItem.jpg";
     $http.post("https://my.api.com/?id=" + item.id).success(
           function (url) {
               item.img = url;
           });
});

在我看来,我曾经有一个带有 ng-src 属性的图像,效果很好:

on my view I used to have an image with ng-src attribute, that worked perfectly like so:

<img  ng-src="{{item.img}}">

然后我决定在 SPAN 上使用背景图像:

Then I've decided to use background-image on a SPAN instead:

<span ng-style="{'background':'transparent url({{item.img}})'}"></span>

现在流程仅在第一次运行时有效,之后我可以看到(在控制台中)以下 html

now the flow works only on the first run, after that I can see (in the console) the following html

<span ng-style="{'background':'transparent url(http://expertsimages.liveperson.com/images/rating/rate10.gif)'}" style="background-image: url(https://fb.lp-chat.com/images/searchItem.jpg); background-color: transparent; background-position: initial initial; background-repeat: initial initial;"></span>

表示变量已更新,但 html 仍处于初始状态.

which indicates that the variable updated, however the html is still on its initial state.

我尝试在发布成功后调用 apply/digest,但出现错误 $digest already in progress(这是有道理的).奇怪的是,在正常的摘要(例如其他 ui 更改)之后,正在应用样式并且我看到了正确的图像.

I tried to call apply/digest on post success, but got an error $digest already in progress (which make sense). The strage thing is that after a normal digest (for example on other ui changes) the style is being applied and I see the right image.

我在这里遗漏了什么?

更新:我创建了一个 JS fiddle 来演示这个问题......看起来像一个错误我.

Update: I've created a JS fiddle that demonstrates this issue...looks like a bug in angular to me.

推荐答案

我也遇到了这个问题.不要使用 {{ }} 进行评估,而是使用字符串 + 值连接.

I ran into this as well. Instead of evaluating with {{ }}, use string + value concatenation.

这会起作用:

<span ng-style="{'background':'transparent url(' + item.img + ')'}"></span>)

这是您的 fiddle

这篇关于AngularJS - ng-style 不更新 css 背景属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆