详细解释ng-src指令在AngularJS中的使用
序
在日常开发工作中,有很多要求在一个页面上显示一些图片。有时,图片的地址路径是由客户端的脚本设置的(可以从数据库中获取)。
这是安古拉杰的时代。当我们想要使用Angularjs在页面上显示图片时,我们将简单地使用:img src=“图像的路径”。
如果我们只考虑显示,毫无疑问是可以的,但是浏览器的控制台上会显示一个404(未找到)错误。
为了解决这个问题,我们需要使用ng-Src。在使用ng-Src之前,我想向您展示一下这个错误是如何发生的
示例代码如下:
示例源代码
Script.js
var testApp=angular。模块(' testModule ',[])。controller('testController ',function($ scope){ var animal={ name : ' CAT ',color: 'White ',picture: '/images/cat.jpg ',};$ scope.animal=animal});Index.html
html ng-app=' test module ' head title/title script src=' http : script/angular . min . js '/script script src=' http : script/js/script . js '/script/head body Div ng-controller=' test controller ' Name : { { animal . Name } } br/Color : { { animal . Color } } br/img src=' http : { { animal . Picture } } '//Div使用模型绑定器,我在页面上使用了这些属性。我对图片使用img HTML标签。
然后运行这个例子,效果如下:
然后打开浏览器控制台,就会看到这个错误。
无法加载资源:服务器响应状态为404(未找到)。
那么问题来了,为什么是这个错误呢?应该如何解决?
原因——解析DOM时,它会尝试从服务器获取图片。此时,src属性上的Angularjs绑定表达式{{ model }}尚未执行,因此未找到错误404。
解决方案——解决后的版本是用ng-Src代替图片中的Src属性。使用此指令后,请求将仅在Angular执行此绑定表达式后发出。
使用ng-Src的例子如下:
html ng-app=' test module ' head title/title script Src=' http : script/angular . min . js '/script script Src=' http : script/js/script . js '/script/head body div ng-controller=' test controller ' name : { { animal . name } } br/color : { { animal . color } } br/img ng-Src=' http : { { animal . picture } }//
定义
Ng-Src-该指令覆盖img/元素的Src本机属性。
摘要
以上就是本文的全部内容。希望你能喜欢。有问题可以留言交流。
版权声明:详细解释ng-src指令在AngularJS中的使用是由宝哥软件园云端程序自动收集整理而来。如果本文侵犯了你的权益,请联系本站底部QQ或者邮箱删除。