I'm loading states for the $stateProvider from a .json file, everything works, but maybe there is a better way to do it without the jQuery ajax call:
config.js
var STATES_FILE = '../config/states.json';
var statesObj,
states;
function configState($stateProvider, $urlRouterProvider, $compileProvider) {
function resolveUrl(path){
var loadUrl = { // Any property in resolve should return a promise and is executed before the view is loaded
loadModule: ['$ocLazyLoad', function($ocLazyLoad) {
// you can lazy load files for an existing module
return $ocLazyLoad.load(path);
}]
};
return loadUrl;
}
// Optimize load start with remove binding information inside the DOM element
$compileProvider.debugInfoEnabled(true);
// Set default state
$urlRouterProvider.otherwise("/dashboard");
// Get states from configuration file
states = $.ajax({
type: 'GET',
url: STATES_FILE,
async: false
})
.responseText;
statesObj = eval("(" + states + ")")
// Load states from states configuration
for(var prop in statesObj){
$stateProvider.state(prop, statesObj[prop]);
}
}
angular
.module('homer')
.config(configState)
.run(function($rootScope, $state) {
$rootScope.$state = $state;
});
And my states.json file:
{
"dashboard": {
"name": "dashboard",
"url": "/dashboard",
"templateUrl": "./views/dashboard.html",
"data": {
"pageTitle": "Dashboard"
}
},
"users": {
"name": "users",
"url": "/users",
"controller": "usersCtrl",
"templateUrl": "/users/views/users.html",
"resolve": "resolveUrl('/users/app/js/compiled/users_app.js')"
},
"invoices": {
"name": "invoices",
"url": "/invoices",
"controller": "invoicesCtrl",
"templateUrl": "/invoices/views/invoices.html",
"resolve": "resolveUrl('/invoices/app/js/compiled/invoices_app.js')"
},
"invoices.upload": {
"name": "invoices.upload",
"url": "/upload",
"controller": "invoicesCtrl",
"templateUrl": "/invoices/views/invoices.html",
"resolve": "resolveUrl('/invoices/app/js/compiled/invoices_app.js')"
},
"reports": {
"name": "reports",
"url": "/reports",
"templateUrl": "./views/reports.html",
"data": {
"pageTitle": "Reports"
}
}
}
From what I've read it's better to use Angular's $q and $http functions. So I tried to solve it with:
function resolveStates($http, $q) {
var deferred = $q.defer();
$http({
method:'GET',
url: STATES_FILE
}).success(function (data) {
deferred.resolve(data);
});
return deferred.promise;
}
But it gives me this error,Uncaught Error: [$injector:modulerr]
You can just make the call
get
by making use of the$http
angular service.What I advise you is to make a controller more or less like the following:
and inside the controller make your request.
For more information about the service
$http
you can check its documentationYou can use an angular factory, it has worked for me. You bring it in the controller as a promise.
For example, to fetch data from your states.json file
FACTORY:
CONTROLLER: