AngularJS中ng-Src指令替代src 解决console的url请求404错误

本文介绍在AngularJS中正确加载图片的方法,避免因提前解析DOM导致的404错误。通过对比src与ng-src的区别,解释如何确保图片路径在AngularJS执行绑定后才发起请求。

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

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

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



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

示例代码如下:

示例源码

Script.js

?
1
2
3
4
5
6
7
8
9
10
11
12
var testApp = angular
         .module( "testModule" , [])
         .controller( "testController" , function ($scope) {
           var animal = {
             name: "CAT" ,
             color: "White" ,
             picture: "/images/cat.jpg" ,
           };
  
           $scope.animal = animal;
  
         });

Index.html

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
< 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 类,它拥有三个属性: NameColor Picture,且已经赋值了。使用模型绑定器,在页面上我使用了这些属性。 对于图片,我使用了 <img> HTML标签 。

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

 

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

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

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

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

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

使用ng-Src的示例如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
< 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原生属性。

/** * Created by wupeng5 on 2016/5/9. */ var app = angular.module("app",['ui.router','oc.lazyLoad','tableKillModule','selectModule',"select2Module"]).config(function($stateProvider,$controllerProvider,$compileProvider,$filterProvider,$provide,$urlRouterProvider,$httpProvider){ $urlRouterProvider.otherwise('login'); //引入$stateProvider对象,为动态路由做准备 app.register = { stateProvider:$stateProvider } //$locationProvider.html5Mode(true); $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'; $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'; $httpProvider.defaults.headers.common["Accept"] = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'; $httpProvider.defaults.headers.post['X-Requested-With'] = 'XMLHttpRequest'; $httpProvider.defaults.transformRequest = [function(data) { /** * The workhorse; converts an object to x-www-form-urlencoded serialization. * @param {Object} obj * @return {String} */ var param = function(obj) { var query = ''; var name, value, fullSubName, subName, subValue, innerObj, i; for (name in obj) { value = obj[name]; if (value instanceof Array) { for (i = 0; i < value.length; ++i) { subValue = value[i]; fullSubName = name + '[' + i + ']'; innerObj = {}; innerObj[fullSubName] = subValue; query += param(innerObj) + '&'; } } else if (value instanceof Object) { for (subName in value) { subValue = value[subName]; fullSubName = name + '[' + subName + ']'; innerObj = {}; innerObj[fullSubName] = subValue; query += param(innerObj) + '&'; } } else if (value !== undefined && value !== null) { query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&'; } } return query.length ? query.substr(0, query.length - 1) : query; }; return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data; }]; //配合nginx处理本地开发, 服务器调式的问题(接口是跨域的) $httpProvider.interceptors.push(function($q){ return { 'request':function(config){ if(config.url.indexOf('html') == -1){ config.url = "" + config.url; } return config || $q.when(config); } } }); //注销RootScope上面的广播事件 //var deregister = $rootScope.$on("rootEvent", function(event,data) { // //}); // //$scope.$on('$destory', function() { // deregister(); // 退订事件 //}); //注册$onRootScope方法,并在执行完毕后直接销毁, 防止内存溢出 $provide.decorator('$rootScope',['$delegate',function($delegate){ Object.defineProperty($delegate.constructor.prototype,'$onRootScope',{ value:function(name,listener){ var unsubscribe = $delegate.$on(name,listener); this.$on('$destroy',unsubscribe); }, enumerable:false }); return $delegate; }]) //使用,不需要手动去销毁这个事件 //$scope.$onRootScope("key",function(){ // console.log("get key"); //}) //$rootScope.$broadcast("key",{name:1}); }); app.factory('timestampMarker', [function() { return { request: function(config) { config.requestTimestamp = new Date().getTime(); return config; }, response: function(response) { response.config.responseTimestamp = new Date().getTime(); return response; } }; }]); app.config(['$httpProvider', function($httpProvider) { $httpProvider.interceptors.push('timestampMarker'); }]); //$http.get('xxxx').then(function(response) { // var time = response.config.responseTimestamp - response.config.requestTimestamp; // console.log('The request took ' + (time / 1000) + ' seconds.'); //}); //当路由变化的时候触发 app.run(function($rootScope,$templateCache) { $rootScope.isLogin = true; $rootScope.loginStyle = ""; $rootScope.$on('$stateChangeStart', function (event, current, previous) { if(current.name != "login" && $rootScope.currentState != current.name){ // console.log($rootScope.currentState); $rootScope.currentState = current.name; } //清理所有template缓存 if (typeof(current) !== 'undefined'){ $templateCache.removeAll(); } $rootScope.currentName = current.name; if($rootScope.currentName == "login"){ $rootScope.isLogin = false; $rootScope.loginStyle = "login"; $rootScope.col = ""; }else{ $rootScope.isLogin = true; $rootScope.loginStyle = ""; } }); });代码审计一下
最新发布
08-23
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值