javascript - 如果我使用 src 而不是 ng-src,angular 仍然如何渲染图像?

标签 javascript angularjs

根据 Angular 文档及其解释,我们应该使用 ng-src而不是 src在图像标记中,图像 url 是一个 Angular 表达式。

例如<img ng-src="{{country.flagURL}}" width="100">

但在我的例子中,如果我使用 src ,浏览器仍然呈现图像。在控制台中,我可以看到一个失败的图像调用,它试图访问像 .../Desktop/%7B%7Bcountry.flagURL%7D%7D 这样的确切表达式。

但是,稍后还有另一个图像调用,它是从 angular.js 发起的,它实际渲染图像并将其显示在浏览器中。

所以我的问题是 - ng-src 有什么用?如果使用 src 也能达到同样的效果?看起来只有一个额外的网络调用会在那里。
当我不使用 ng-src 时,渲染图像的 Angular 到底发生了什么? ?

下面是我的代码片段。你可以跑过去看看。

<html ng-app="countryApp">
  <head>
    <meta charset="utf-8">
    <title>Angular.js Example</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
    <script>
      var countryApp = angular.module('countryApp', []);
      countryApp.controller('CountryCtrl', function ($scope, $http){
        data = [
        {
          "name": "China",
          "population": 1359821000,
          "flagURL": "https://upload.wikimedia.org/wikipedia/commons/f/fa/Flag_of_the_People%27s_Republic_of_China.svg"
        },
        {
          "name": "India",
          "population": 1205625000,
          "flagURL": "https://upload.wikimedia.org/wikipedia/en/4/41/Flag_of_India.svg"
        },
        {
          "name": "United States of America",
          "population": 312247000,
          "flagURL": "https://upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg"
        }
      ];
          $scope.countries = data;
      });

    </script>
  </head>
  <body ng-controller="CountryCtrl">
    <table>
      <tr>
        <th>Country</th>
        <th>Population</th>
        <th>Flag</th>
      </tr>
      <tr ng-repeat="country in countries">
        <td>{{country.name}}</td>
        <td>{{country.population}}</td>
        <td><img src="{{country.flagURL}}" width="100"></td>
      </tr>
    </table>
  </body>
</html>

最佳答案

<img ng-src="{{country.flagURL}}" width="100">

在计算 ng-src 中的表达式之前,Angular 不会加载图像。

但是,

<img src="{{country.flagURL}}" width="100">

浏览器尝试使用原始(未评估)表达式加载图像,这导致对服务器的 GET 请求失败。但是,一旦 Angular 加载并评估 src 标签下的表达式,浏览器就会使用新的 url 值重新呈现图像标签。

所以简而言之,ng-src 只是停止加载图像,直到 angular 执行表达式以避免初始无效请求(具有无效 URL)。检查 ng-src 的实现 here .它只是添加了 src 标签图像,导致对图像的 GET 请求。

关于javascript - 如果我使用 src 而不是 ng-src,angular 仍然如何渲染图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37046546/

相关文章:

javascript - vue.js 获取 App.vue 中的路由名称

javascript - 尽管使用了 on(),但在将元素添加到 DOM 后,Jquery 单击事件不会触发

javascript - 如果未启用 javascript,则定义 css

javascript - 选择单选按钮时显示 div

html - Controller 和函数如何使用 .emit 在两个单独的文件之间进行通信,以及如何在 AngularJS 中告诉 Controller 层次结构?

javascript - 自定义过滤器中的 Angular 转换问题

javascript - 编程定时器

javascript - 如何使用 jQuery/ajax 发出 GET 请求?

javascript - 如何将函数返回到作用域变量中?

javascript - 如何安全地清理指令中的 AngularJS 事件绑定(bind)