I'm creating my frist AngularJS application.
I have a kind of problem with my Index page. There can be two different templates depending if User is authenticated or not.
My idea is to have a MainController defined before ng-view and a view controller (indexController, aboutController, ...) depending which view is displayed.
I've made a service UserService which mission is to get user's data from my server and serve them to controllers.
The problem is I want my MainController to get the user's data.
I've read things about resolve and promise but it only works with view controllers because it's defined in $routeProvider.
My question is how can I initialize my MainController data before executing my app routes ?
PS : A bit of code to help
index.html
<div id="page" ng-controller="MainController as Main">
<div id="navbar-container" class="shadow1">
<navbar></navbar>
</div>
<div class="row">
<div id="page-container" class="large-12 columns">
<div ng-view></div>
</div>
</div>
</div>
mainController.js
...
define([], function()
{
return angular.module('MyApp.controllers', []).controller('MainController', ['$scope', '$http', 'UserService', function($scope, $http, UserService)
{
// I want this to be defined before executing the app //
$scope.currentUser = UserService.getCurrentUser();
}]);
});
...
userService.js
define(['angular'], function (angular)
{
return angular.module('MyApp.services', []).service('UserService', ['$http', function($http)
{
var _currentUser = null;
var _promise = (_currentUser !== null) ? _currentUser : $http.get('/api/user').success(function(data)
{
_currentUser = data.result;
});
return {
promise : _promise,
getCurrentUser : function()
{
return _currentUser;
},
isAuthenticated : function()
{
return (_currentUser !== null);
},
};
}
]);
});
Maybe there is another way to do what I expect but i'm really a noob with AngularJS. I really would appreciate some help.
Thank you in advance.