As explained here, the AngularJS directive ng-src is used to prevent the browser from loading the resource (e.g. image) before the handlebars get parsed. I'm currently using the following code:
<div ng-controller="MyCtrl"> <img ng-src="http://localhost:8081/media/{{ path }}" /> </div>
With the following JavaScript:
function MyCtrl($scope, $timeout) { $timeout(function () { $scope.path = 'images/23694c70-04d7-11e3-9ba8-73fb00de24c4.png'; }, 1000); };
The path is being retrieved from a webservice. Because of this delay, the browser tries to load http://localhost:8081/media/
, which causes a 404. Once the path is retrieved, the browser issues the correct request and loads the image.
What is the preferred method to prevent loading any resources until all data is ready?
Please see jsfiddle for an example illustrating my situation.
AngularJS ng-src Directive The ng-src directive overrides the original src attribute of an <img> element. The ng-src directive should be used instead of src if you have AngularJS code inside the src value. The ng-src directive makes sure the image is not displayed wrong before AngularJS has evaluated the code.
The ng-app directive defines the root element of an AngularJS application. The ng-app directive will auto-bootstrap (automatically initialize) the application when a web page is loaded.
The $ in AngularJs is a built-in object.It contains application data and methods.
The ng-click directive tells AngularJS what to do when an HTML element is clicked.
Put the whole path inside the $scope variable. That way ng-src
will wait until you provide it with the fully resolved path to the image:
<div ng-controller="MyCtrl"> <img ng-src="{{ path }}" /> </div>
function MyCtrl($scope, $timeout) { var path = 'https://si0.twimg.com/profile_images/'; $timeout(function () { $scope.path = path + '2149314222/square.png'; }, 1000); };
FIDDLE
Let's take this blogitem directive
. The examples above already show you how to set a default value.
HTML :
<blogitem ng-repeat="item in items" bg-src="{{ item.image }}" caption="{{ item.title }}"/>
JS :
.directive( 'blogitem', function() { return { restrict : 'E', templateUrl : 'js/app/directives/blogitem.html', replace : true, // pass these two names from attrs into the template scope scope : { intro : '@', bgSrc : '@' } } } )
HTML template :
<article> <img ng-src="{{ bgSrc }}"/> <p>{{ intro }}</p> </article>
Hopefully it helps by your understanding of the ng-src
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With