Skip to content

Commit 94c9258

Browse files
committed
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 61eb426 commit 94c9258

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/ng/directive/ngInclude.js

+11
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,16 @@
147147
* @description
148148
* Emitted every time the ngInclude content is reloaded.
149149
*/
150+
151+
152+
/**
153+
* @ngdoc event
154+
* @name ng.directive:ngInclude#$includeContentError
155+
* @eventOf ng.directive:ngInclude
156+
* @eventType emit on the scope ngInclude was declared in
157+
* @description
158+
* Emitted when a template HTTP request yields an erronous response (status < 200 || status > 299)
159+
*/
150160
var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$animate', '$sce',
151161
function($http, $templateCache, $anchorScroll, $animate, $sce) {
152162
return {
@@ -208,6 +218,7 @@ var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$animate'
208218
scope.$eval(onloadExp);
209219
}).error(function() {
210220
if (thisChangeId === changeCounter) cleanupLastIncludeContent();
221+
scope.$emit('$includeContentError');
211222
});
212223
scope.$emit('$includeContentRequested');
213224
} 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)