Inputting a default image in case the src attribute of an html

后端 未结 22 2438
渐次进展
渐次进展 2020-11-22 16:02

Is there any way to render a default image in an HTML tag, in case the src attribute is invalid (using only HTML)? If not, what would

22条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 16:24

    If you are using Angular 1.x you can include a directive that will allow you to fallback to any number of images. The fallback attribute supports a single url, multiple urls inside an array, or an angular expression using scope data:

    
    
    
    

    Add a new fallback directive to your angular app module:

    angular.module('app.services', [])
        .directive('fallback', ['$parse', function ($parse) {
            return {
                restrict: 'A',
                link: function (scope, element, attrs) {
                    var errorCount = 0;
    
                    // Hook the image element error event
                    angular.element(element).bind('error', function (err) {
                        var expressionFunc = $parse(attrs.fallback),
                            expressionResult,
                            imageUrl;
    
                        expressionResult = expressionFunc(scope);
    
                        if (typeof expressionResult === 'string') {
                            // The expression result is a string, use it as a url
                            imageUrl = expressionResult;
                        } else if (typeof expressionResult === 'object' && expressionResult instanceof Array) {
                            // The expression result is an array, grab an item from the array
                            // and use that as the image url
                            imageUrl = expressionResult[errorCount];
                        }
    
                        // Increment the error count so we can keep track
                        // of how many images we have tried
                        errorCount++;
                        angular.element(element).attr('src', imageUrl);
                    });
                }
            };
        }])
    

提交回复
热议问题