Error Wrapper Directive
by Josh Carroll
HTML
<script src="http://code.angularjs.org/1.2.0-rc.3/angular.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<script src="http://code.angularjs.org/1.2.0-rc.3/angular-route.min.js"></script>
<!-- Ugly Hack to make AngularJS routing work inside of jsFiddle -->
<base href="/" />
<ul class="nav nav-pills" ng-controller="navController as navCtrl">
<li><a href ng-click="navCtrl.goTo('/view1')">View 1</a></li>
<li><a href ng-click="navCtrl.goTo('/good')">Good</a></li>
<li><a href ng-click="navCtrl.goTo('/error')">Error</a></li>
</ul>
<div class="container">
<data-error-view>
<h2>I'm Transcluded <small>don't I sound smart</small></h2>
<div data-ng-view></div>
</data-error-view>
</div>
JavaScript
var Directives;
(function (Directives) {
var Error = function ($rootScope) {
return {
restrict: 'E',
transclude: true,
template: "<div class='alert alert-danger' data-ng-if='routeChangeError'>An Error Occured</div>" +
"<div data-ng-if='!routeChangeError' data-ng-transclude></div>",
link: function (scope, elem, attrs) {
$rootScope.$on('$routeChangeError', function () {
scope.routeChangeError = true;
});
$rootScope.$on('$routeChangeSuccess', function () {
scope.routeChangeError = false;
});
}
};
};
Error.$inject = ['$rootScope'];
Directives.Error = Error;
}(Directives || (Directives = {})));
(function () {
angular.element(document).ready(function () {
var module = angular.module('demo', ['ngRoute']);
module.directive('errorView', Directives.Error);
module.controller('navController', ['$location', function($location){
$location.path('/good');
this.goTo = function(viewPath){
$location.path(viewPath);
};
}]);
module.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider
.when('/view1', {
template: '<div class="alert alert-default">I\'m a plain ole route</div>'
})
.when('/good', {
template: '<div class="alert alert-success">I\'m a happy route!</div>'
}).when('/error', {
template: '<div>You should never see me!</div>',
resolve: {
badStuff: ['$q', '$timeout', function ($q, $timeout) {
var def = $q.defer();
$timeout(function () {
def.reject("Rejected!!!");
...