Route With Factory

by Willian Tamagi

HTML

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
<script type="text/ng-template" id="embedded.home.html">
    <h1> Home </h1>
</script>

<script type="text/ng-template" id="embedded.about.html">
    <h1> About </h1>
</script>

<div ng-controller="myController"> 
  <div ng-show="auth.error()">
    {{auth.error()}}
  </div>
  <div ng-show="auth.success()">
    {{auth.success()}}
  </div>
  <div id="navigation">  
    <a href="#/home">Home</a>
    <a href="#/about">About</a>
  </div>

  <div ng-view></div>
</div>

JavaScript

var myApp = angular.module('myApp', ['ngRoute', 'appServer']);

myApp.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.
    when('/home', {
        templateUrl: 'embedded.home.html',
        controller: 'HomeController'
    }).
    when('/about', {
        templateUrl: 'embedded.about.html',
        controller: 'AboutController'
    }).
    otherwise({
        redirectTo: '/home'
    });
}]);

myApp.controller('myController', function ($scope, Auth) {
  $scope.auth = Auth;
});

myApp.controller('HomeController', function ($scope, Auth) {
	Auth.setSuccess('SUCCESSSSSSSSSSSSSSS!!!');
});

myApp.controller('AboutController', function ($scope, Auth) {
	Auth.setError('ERRORRRRRRRRRRRRRR!!!');
});

angular.module('appServer', [])
.factory('Auth', function($rootScope){
  var success = null;
  var error = null;
  return {
    success:function(){
      return success;
    },
    setSuccess:function(newStatus){
      success = newStatus;
      error = null;
    },
    error:function(){
      return error;
    },
    setError:function(newStatus){
      error = newStatus;
      success = null;
    }
  }
});