Skip to content

Commit 85a53ea

Browse files
rphvgkalpak
authored andcommitted
fix($compile): properly handle setting srcset to undefined
Previously, calling `Attributes#$set('srcset', value)` on an `<img>` element would throw if `value` were undefined, as it assumed `value` is always a string. This commit fixes the issue, by skipping the unnecessary string manipulation when `value` is not defined. Closes angular#14470 Closes angular#14493
1 parent 2d87ef8 commit 85a53ea

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

src/ng/compile.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -1153,7 +1153,7 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
11531153
(nodeName === 'img' && key === 'src')) {
11541154
// sanitize a[href] and img[src] values
11551155
this[key] = value = $$sanitizeUri(value, key === 'src');
1156-
} else if (nodeName === 'img' && key === 'srcset') {
1156+
} else if (nodeName === 'img' && key === 'srcset' && isDefined(value)) {
11571157
// sanitize img[srcset] values
11581158
var result = "";
11591159

test/ng/compileSpec.js

+21
Original file line numberDiff line numberDiff line change
@@ -7602,6 +7602,27 @@ describe('$compile', function() {
76027602

76037603
describe('img[srcset] sanitization', function() {
76047604

7605+
it('should not error if undefined', function() {
7606+
var linked = false;
7607+
module(function() {
7608+
directive('setter', valueFn(function(scope, elem, attrs) {
7609+
attrs.$set('srcset', 'http://example.com/');
7610+
expect(attrs.srcset).toBe('http://example.com/');
7611+
7612+
attrs.$set('srcset', undefined);
7613+
expect(attrs.srcset).toBeUndefined();
7614+
7615+
linked = true;
7616+
}));
7617+
});
7618+
inject(function($compile, $rootScope) {
7619+
element = $compile('<img setter></img>')($rootScope);
7620+
7621+
expect(linked).toBe(true);
7622+
expect(element.attr('srcset')).toBeUndefined();
7623+
});
7624+
});
7625+
76057626
it('should NOT require trusted values for img srcset', inject(function($rootScope, $compile, $sce) {
76067627
element = $compile('<img srcset="{{testUrl}}"></img>')($rootScope);
76077628
$rootScope.testUrl = 'http://example.com/image.png';

test/ng/directive/ngSrcsetSpec.js

+5
Original file line numberDiff line numberDiff line change
@@ -28,5 +28,10 @@ describe('ngSrcset', function() {
2828
$rootScope.$digest();
2929
expect(element.attr('srcset')).toBe('http://example.com/image1.png 1x,unsafe:javascript:doEvilStuff() 2x');
3030
}));
31+
32+
it('should not throw an error if undefined', inject(function($rootScope, $compile) {
33+
element = $compile('<img ng-attr-srcset="{{undefined}}">')($rootScope);
34+
$rootScope.$digest();
35+
}));
3136
});
3237

0 commit comments

Comments
 (0)