当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > 详解AngularJS中ng-src指令的使用

详解AngularJS中ng-src指令的使用

2018年05月10日  | 移动技术网IT编程  | 我要评论

前言

在日常开发工作中,有很多需求是在一个页面上显示一些图片。有时,图片的地址路径是由客户端的脚本来设置(它有可能是从数据库中获取的)。

这是angularjs的时代,当我们想使用angularjs来实现在页面中展示图片,我们会简单使用: <img src=”path of image”>.

如果我们只考虑展示,毫无疑问它没问题,但是在浏览器的控制台中会显示一个 404 (not found) 错误。

为了解决这个问题,我们需要使用ng-src。在使用 ng-src之前,我想给你重现一下这个错误是如何产生的

示例代码如下:

示例源码

script.js

var testapp = angular 
        .module("testmodule", []) 
        .controller("testcontroller", function ($scope) { 
          var animal = { 
            name: "cat", 
            color: "white", 
            picture: "/images/cat.jpg", 
          }; 
 
          $scope.animal = animal; 
 
        }); 

<html ng-app="testmodule"> 
<head> 
  <title></title> 
  <script src="scripts/angular.min.js"></script> 
  <script src="scripts/js/script.js"></script> 
</head> 
<body> 
   
  <div ng-controller="testcontroller"> 
    name: {{animal.name}} 
    <br /> 
    color: {{animal.color}} 
    <br /> 
    <img src="{{animal.picture}}" /> 
 
  </div> 
</body> 
</html> 

在上述例子 中,有一个 animal 类,它拥有三个属性: name, color picture,且已经赋值了。使用模型绑定器,在页面上我使用了这些属性。 对于图片,我使用了 <img> html标签 。

然后运行这个示例,效果如下:

 

然后打开浏览器的控制台,就会看到这个错误。

无法加载资源:服务器响应状态为404 (not found)。

那么问题来了,为什么会出现这个错误?应该如何解决?

原因- 当dom 被解析时,会尝试从服务器获取图片。 这时,src属性上的 angularjs 绑定表达式 {{ model }}还没有执行,所以就出现了  404 未找到的错误。

解决方案- 解决的版本就是:在图片中使用ng-src代替src属性,使用这个指令后,请求就只会在angular执行这个绑定表达式之后才会发出。

使用ng-src的示例如下:

<html ng-app="testmodule"> 
<head> 
  <title></title> 
  <script src="scripts/angular.min.js"></script> 
  <script src="scripts/js/script.js"></script> 
</head> 
<body> 
  <div ng-controller="testcontroller"> 
    name: {{animal.name}} 
    <br /> 
    color: {{animal.color}} 
    <br /> 
    <img ng-src="{{animal.picture}}" /> 
 
  </div> 
</body> 
</html> 

现在你再打开浏览器的控制台,就不会出现:404 未找到, 这是因为使用了ng-src

定义

ng-src- 这个指令覆盖了<img />元素的src原生属性。

总结

以上就是这篇文章的全部内容,希望大家能够喜欢,如果有疑问可以留言交流。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网