add support for 404 handling via $route.otherwise

Closes #217
This commit is contained in:
Igor Minar 2011-01-30 16:57:57 -08:00
parent 7db3b54c1f
commit ce7ab3d1ee
2 changed files with 62 additions and 0 deletions

View file

@ -702,6 +702,22 @@ angularServiceInject('$route', function(location) {
if (params) extend(route, params);
dirty++;
return route;
},
/**
* @workInProgress
* @ngdoc method
* @name angular.service.$route#otherwise
* @methodOf angular.service.$route
*
* @description
* Sets route definition that will be used on route change when no other route definition
* is matched.
*
* @param {Object} params Mapping information to be assigned to `$route.current`.
*/
otherwise: function(params) {
$route.when(null, params);
}
};
function updateRoute(){
@ -719,12 +735,26 @@ angularServiceInject('$route', function(location) {
}
}
});
//fallback
if (!childScope && routes[_null]) {
childScope = createScope(parentScope);
$route.current = extend({}, routes[_null], {
scope: childScope,
params: extend({}, location.hashSearch)
});
}
//fire onChange callbacks
forEach(onChange, parentScope.$tryEval);
if (childScope) {
childScope.$become($route.current.controller);
}
}
this.$watch(function(){return dirty + location.hash;}, updateRoute);
return $route;
}, ['$location']);

View file

@ -411,6 +411,38 @@ describe("service", function(){
expect($route.current.controller).toBeUndefined();
expect(onChangeSpy).toHaveBeenCalled();
});
it('should handle unknown routes with "otherwise" route definition', function() {
var scope = angular.scope(),
$location = scope.$service('$location'),
$route = scope.$service('$route'),
onChangeSpy = jasmine.createSpy('onChange');
function NotFoundCtrl() {this.notFoundProp = 'not found!'}
$route.when('/foo', {template: 'foo.html'});
$route.otherwise({template: '404.html', controller: NotFoundCtrl});
$route.onChange(onChangeSpy);
expect($route.current).toBeNull();
expect(onChangeSpy).not.toHaveBeenCalled();
$location.updateHash('/unknownRoute');
scope.$eval();
expect($route.current.template).toBe('404.html');
expect($route.current.controller).toBe(NotFoundCtrl);
expect($route.current.scope.notFoundProp).toBe('not found!');
expect(onChangeSpy).toHaveBeenCalled();
onChangeSpy.reset();
$location.updateHash('/foo');
scope.$eval();
expect($route.current.template).toEqual('foo.html');
expect($route.current.controller).toBeUndefined();
expect($route.current.scope.notFoundProp).toBeUndefined();
expect(onChangeSpy).toHaveBeenCalled();
});
});