I am currently in the process of developing a dynamic framework using AngularJS. My plan involves allowing users to add new templateUrl and controller from a JSON file, like the one shown in templates.json:
{
"pages" : [
{
"name" : "home",
"tempUrls" : "views/home",
"controller" : "HomeController"
},
{
"name" : "about",
"tempUrls" : "views/about",
"controller" : "AboutController"
},
{
"name" : "contact",
"tempUrls" : "views/contact",
"controller" : "ContactController"
}
]
}
Our task is to create the controller and templateUrl for each page in AngularJS based on the information provided in the JSON file, such as hours.js:
var hours = angular.module('hours', ['ngRoute']);
var $routeProviderReference;
var currentRoute;
hours.config(function($routeProvider){
$routeProviderReference = $routeProvider;
})
.run(['$route', '$http', '$rootScope', function($route, $http, $rootScope){
$http.get("templates.json").success(function(data){
var loop = 0, currentRoute;
for(loop = 0; loop < data.pages.length; loop++){
currentRoute = data.pages[loop];
var routeName = "/" + currentRoute.name;
$routeProviderReference.when(routeName, {
templateUrl: currentRoute.tempUrls,
controller : currentRoute.controller,
resolve: {
param: function()
{
return currentRoute.resolve;
}
}
});
}
$route.reload();
});
}]);
hours.controller(currentRoute.controller, function($scope){
$scope.pageClass = 'page-' + currentRoute.name;
});
Next, we have the index.html file:
<div ng-class="{{pageClass}}" ng-view></div>
Before converting to a dynamic version, here is the static example using AngularJS:
var hours = angular.module('hours', ['ngRoute']);
hours.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'views/page-home.html',
controller: 'homeController'
})
});
hours.controller('homeController', function($scope){
$scope.pageClass = 'page-home';
});
If anyone can provide assistance, it would be greatly appreciated!