Skip to content

Commit e4419da

Browse files
caitpbtford
authored andcommitted
feat(ngInclude): emit $includeContentError when HTTP request fails
This adds a scope event notification when a template fails to load. This can have performance implications, and unfortunately cannot at this moment be terminated with preventDefault(). But it's nice to be notified when problems occur! Closes angular#5803
1 parent 63ea0c1 commit e4419da

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

src/ng/directive/ngInclude.js

+14-1
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,16 @@
159159
* @description
160160
* Emitted every time the ngInclude content is reloaded.
161161
*/
162+
163+
164+
/**
165+
* @ngdoc event
166+
* @name ng.directive:ngInclude#$includeContentError
167+
* @eventOf ng.directive:ngInclude
168+
* @eventType emit on the scope ngInclude was declared in
169+
* @description
170+
* Emitted when a template HTTP request yields an erronous response (status < 200 || status > 299)
171+
*/
162172
var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$animate', '$sce',
163173
function($http, $templateCache, $anchorScroll, $animate, $sce) {
164174
return {
@@ -227,7 +237,10 @@ var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$animate'
227237
currentScope.$emit('$includeContentLoaded');
228238
scope.$eval(onloadExp);
229239
}).error(function() {
230-
if (thisChangeId === changeCounter) cleanupLastIncludeContent();
240+
if (thisChangeId === changeCounter) {
241+
cleanupLastIncludeContent();
242+
scope.$emit('$includeContentError');
243+
}
231244
});
232245
scope.$emit('$includeContentRequested');
233246
} else {

test/ng/directive/ngIncludeSpec.js

+23
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,29 @@ describe('ngInclude', function() {
143143
}));
144144

145145

146+
it('should fire $includeContentError event when content request fails', inject(
147+
function($rootScope, $compile, $httpBackend, $templateCache) {
148+
var contentLoadedSpy = jasmine.createSpy('content loaded'),
149+
contentErrorSpy = jasmine.createSpy('content error');
150+
151+
$rootScope.$on('$includeContentLoaded', contentLoadedSpy);
152+
$rootScope.$on('$includeContentError', contentErrorSpy);
153+
154+
$httpBackend.expect('GET', 'tpl.html').respond(400, 'nope');
155+
156+
element = $compile('<div><div ng-include="template"></div></div>')($rootScope);
157+
158+
$rootScope.$apply(function() {
159+
$rootScope.template = 'tpl.html';
160+
});
161+
$httpBackend.flush();
162+
163+
expect(contentLoadedSpy).not.toHaveBeenCalled();
164+
expect(contentErrorSpy).toHaveBeenCalledOnce();
165+
expect(element.children('div').contents().length).toBe(0);
166+
}));
167+
168+
146169
it('should evaluate onload expression when a partial is loaded', inject(
147170
putIntoCache('myUrl', 'my partial'),
148171
function($rootScope, $compile) {

0 commit comments

Comments
 (0)