NgSrc evaluates to ngIf, causing an unnecessary HTTP request

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 the tag and evaluate src. The browser will make an http request for img/_img.png wchich does not exist. Angular will then remove the tag after parsing the ngIf directive. What is the easiest way to solve this problem? I thought this was the perfect use case for ngSrc and ngIf.

EDIT

The current unstable version 1.2.0-rc.2 is fixed and everything works as it should be done. In the current stable 1.0.8, you cannot even use the three-dimensional operator.

+4
source share
2 answers

You do not need the ng-if directive for this. Just do a ternary operator test in your expression. Sort of

<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

+14
source

You can do 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.org/1.2.0-rc.2/angular.js"></script> <script src="http://code.jquery.com/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($compile){ return { link: function(scope, element, attrs){ if(scope.image.name != null){ $compile($(element).attr('ng-src', 'http://lauterry.imtqy.com/slides-prez-angular/img/angularjs.png'))(scope); } } } }); 

Here is a complete working example: http://plnkr.co/edit/LNgsuX

+2
source

Source: https://habr.com/ru/post/1502849/


All Articles