简体   繁体   中英

AngularJS ngSrc - default path if current path not exist

I use this image html tag with angularJS'S ngSrc like this:

 <img data-ng-src="assets/img/{{documentFile.ending}}.PNG" alt="" title="Dateiendung {{documentFile.ending}}" />

Is there a way that ngSrc use another path if documentFile.ending does not exist - something like if not exist than use a default path ?

The ngSrc directive doesn't have that functionality.

You can check if a resource exists by using the $http service:

 // app.js (function() { 'use strict'; angular.module('app', []); })(); // main.controller.js (function() { 'use strict'; angular.module('app').controller('MainController', MainController); MainController.$inject = ['$http']; function MainController($http) { var vm = this; // set image uri's var myImageUri = "http://example.com/myimagedoesntexist.png"; var myFallbackImageUri = "http://placehold.it/350x150?text=My+fallback+image"; // make a http get request to check if the image exists $http.get(myImageUri).then(function() { // successful response status code so image exists // use image uri vm.myImageUri = myImageUri; }, function() { // non-success response status code so image does not exist // use fallback image uri vm.myImageUri = myFallbackImageUri; }); } })(); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app" ng-controller="MainController as MainCtrl"> <img data-ng-src="{{MainCtrl.myImageUri}}" alt="..." title="" /> </div> 

Yes, you can use the logical operator || , which return the value of the second operand if the first is falsy

<img data-ng-src="assets/img/{{documentFile.ending || 'default-image.png'}}.PNG" alt="" title="Dateiendung {{documentFile.ending}}" />

If documentFile.ending has a truthy value(ie an string) but the image doesn't exists on the server, you can write a simple directive for handle the error.

 angular.module('test', []) .controller('test', function ($scope) { $scope.correct_image = 'https://unsplash.it/200'; $scope.wrong_image = 'https://unsplas123123h.it/200'; }) .directive('imageDispatch', function () { return { restrict: 'AE', link: function (scope, element, attrs) { element.bind('load', function () { console.log('image loaded'); }).bind('error', function () { element.attr('src', 'http://www.safexone.com/images/old/default.gif'); }); } } }); 
 <div ng-app="test" ng-controller="test"> <h3>Correct image</h3> <img ng-src="{{correct_image}}" image-dispatch /> <h3>Wrong image</h3> <img ng-src="{{wrong_image}}" image-dispatch /> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM