JSFiddle - React, Tailwind, and code Playground
by Dũng Hoàng Ngọc
HTML
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular-route.min.js"></script>
<div id="code">
<ng-view></ng-view>
</div>
JavaScript
$(document).ready(function() {
angular.module('app.auth', [])
.factory('AuthService', ['$q', function ($q) {
return {
_user: null,
setUser: function (user) {
this._user = user;
},
getUser: function () {
return this._user;
},
fetchUser: function () {
var defer = $q.defer();
var _this = this;
setTimeout(function() {
_this.setUser({});
console.log('Has User:' + _this.getUser());
defer.resolve();
}, 500);
defer.promise;
}
}
}])
.run(['$rootScope', '$location', '$timeout', 'AuthService', function ($rootScope, $location, $timeout, AuthService) {
$rootScope.$on("$locationChangeStart", function (event) {
var path = $location.path();
var user = AuthService.user;
console.log('locationChangeStart trigger: ', user);
if (!user && path === '/') {
event.preventDefault();
$timeout(function() {
//I dont know why i have to use $timeout, and this thing work ???
$location.path('/login');
});
}
});
}]);
angular.module('app', ['ngRoute', 'app.auth'])
.controller('DashboardCtrl', function ($scope) {
$scope.name = "User";
})
.controller('LoginCtrl', function ($scope) {
})
.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
template: '<h1>Dashboard {{name}}</h1>',
controller: 'DashboardCtrl'
}).
when('/login',...