admin管理员组文章数量:1242842
When you write something like:
<img ng-if="image.name != null" ng-src="img/{{ image.name }}_img.png" />
If image.name = null
Angular will first add tag and evaluate src. The browser will make http request for img/_img.png
wchich doesn't exists. Then angular will remove tag after parsing ngIf directive. What is the simplest way to resolve this issue? I thought that it's perfect use case for ngSrc and ngIf.
EDIT
In current unstable 1.2.0-rc.2 issue is fixed and everything works how it is supposed to do. In current stable 1.0.8 you can't even use ternary operator.
When you write something like:
<img ng-if="image.name != null" ng-src="img/{{ image.name }}_img.png" />
If image.name = null
Angular will first add tag and evaluate src. The browser will make http request for img/_img.png
wchich doesn't exists. Then angular will remove tag after parsing ngIf directive. What is the simplest way to resolve this issue? I thought that it's perfect use case for ngSrc and ngIf.
EDIT
In current unstable 1.2.0-rc.2 issue is fixed and everything works how it is supposed to do. In current stable 1.0.8 you can't even use ternary operator.
Share Improve this question edited Sep 19, 2013 at 7:46 p2004a asked Sep 18, 2013 at 15:23 p2004ap2004a 1332 silver badges7 bronze badges 1- Make a directive that will check the ng-if and if the name is not null pile the ng-src. I'll try a plunkr if you want – Thomas Pons Commented Sep 18, 2013 at 15:25
2 Answers
Reset to default 14You don't need the ng-if
directive for this. Just do a ternary operator test in your expression. Something like
<img ng-src="{{image.name?('img/'+ image.name +'_img.png'):null}}"/>
and it should work. See my plunker http://plnkr.co/edit/BWiGdO?p=preview
You can do it like this with a simple directive.
Here is the HTML :
<!DOCTYPE html>
<html ng-app="App">
<head>
<link rel="stylesheet" href="style.css">
<script src="http://code.angularjs/1.2.0-rc.2/angular.js"></script>
<script src="http://code.jquery./jquery-2.0.3.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MyCtrl">
<h1>Hello Plunker!</h1>
<img ng-directive />
</body>
</html>
Here is the directive with the controller :
angular.module('App', [])
.controller('MyCtrl', function($scope){
$scope.image = {name: "myName"};
});
angular.module('App')
.directive('ngDirective', function($pile){
return {
link: function(scope, element, attrs){
if(scope.image.name != null){
$pile($(element).attr('ng-src', 'http://lauterry.github.io/slides-prez-angular/img/angularjs.png'))(scope);
}
}
}
});
Here is the plete working example : http://plnkr.co/edit/LNgsuX
本文标签: javascriptngSrc is computed before ngIf causing unnecessary http requestStack Overflow
版权声明:本文标题:javascript - ngSrc is computed before ngIf causing unnecessary http request - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740087827a2223842.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论