javascript - 浏览器尝试在 ng-repeat 处理之前渲染图像

标签 javascript html angularjs

我有一个简单的案例:一些对象通过 ng-repeat 输出到 html 页面。每个对象都有一条要显示的图像路径。问题是:尽管我有一个空的对象数组,但浏览器似乎尝试使用不正确的 URL 加载图像(我通过 firebug 看到 404 错误)。代码:

<ul class="thumbnails">
  <div class="row-fluid" ng-repeat="item in searchItems" ng-if="$index%2==0">
    <div class="span5" ng-repeat="item in searchItems|limitTo:2:$index">
      <div class="thumbnail" style="border-style:none;box-shadow: 0 0 0 0;">
        <b>{{item.name}}</b><br>
        <img height="160" src="{{item.imageUrl}}" class="img-rounded"><br>
      </div><!--thumbnail-->
    </div><!--span-->
  </div>
</ul>

我在 Firebug 中看到的错误:

NetworkError: 404 Not Found - http://localhost:8000/app/%7B%7Bitem.imageUrl%7D%7D

所以看起来浏览器会在 angularjs 处理其指令之前尝试加载图像。除了这个错误之外,一切都运行良好。但是,我想消除这个问题。我怎样才能做到这一点?

最佳答案

使用ng-src。这是 angular.js 解决这个问题的方法。 ng-src 可以防止浏览器“抢先一步”,只有在 item.imageUrl 的值得到正确解析后才加载图像。

引用Angular docs在 ng-src 上:

Using Angular markup like {{hash}} in a src attribute doesn't work right: The browser will fetch from the URL with the literal text {{hash}} until Angular replaces the expression inside {{hash}}. The ngSrc directive solves this problem.

因此,您的代码将变为:

<img height="160" ng-src="{{item.imageUrl}}" class="img-rounded"><br>

关于javascript - 浏览器尝试在 ng-repeat 处理之前渲染图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34299442/

相关文章:

javascript - 动态更改 iframe 标记源的脚本

javascript - 如何设置复杂的 jquery 函数?

javascript - 使用 Angular 简单上一个\下一个 slider

javascript - 在没有 $scope 的情况下将值从输入传递到 Controller

javascript - 纯空格字符串的长度?

javascript - 如何使用 Ember.js 编写单元测试套件?

javascript - 使用 jquery 显示简单的 carousal 描述

javascript - 使用 JavaScript 拆分字符串

javascript - 如何根据另一个下拉菜单值禁用下拉菜单

javascript - anchor 导航后如何向下滚动页面?