So far I have the ability to generate new HTML pages with PHP code. I already have some pages, but I can generate new with a click of a button. It sets it up in such a way that it stores all of its information in JSON file with: name of the file, "when" component for angular route provider, the templateUrl, and a controller name.
Here is an example of JSON file:
{
"pages": [
{
"name": "index",
"when": "/",
"controller": "indexController",
"template": "views/index.html"
}
]
}
I need somehow to bind the controllers to these generated pages, so that they will point to my HTML code with ng-view.
My HTML code has this:
<div ng-view class="{{pageClass}}"></div>
My static Angular code had this (written manually, not generated dynamically):
app.config(function($routeProvider){
$routeProvider.
when('/', {
templateUrl: '/views/index.html',
controller: 'indexController'
});
app.controller('indexController', function($scope) {
$scope.pageClass = 'index';
});
The controller allowed me to insert index.html template onto the ng-view section with class="{{pageClass}}". (I also could have used ng-class="{pageClass}")
Now, however, I generate the pages dynamically, which doesn't register controllers and binds the templates to the pageClass:
var app = angular.module('myApp', ['ngRoute']);
var $routeProviderReference;
app.config(['$routeProvider', function($routeProvider) {
$routeProviderReference = $routeProvider;
}]);
app.run(['$route','$http','$rootScope',function($route, $http, $rootScope){
$http.get('temp.json') // load data
.then(function(data){
var result = data.data.pages; // data from JSON file
var i;
var currentRoute;
for (i = 0; i< result.length; i++){ // for every existing HTML page
currentRoute = result[i];
var routeName = currentRoute.when;
$routeProviderReference.when(routeName, { // assign template and controller
templateUrl: currentRoute.template,
controller: currentRoute.controller
});
}
$route.reload();
});
}]);
I get an error with this method, even though is partially works: Error: [$controller:ctrlreg]
How do I bind my controllers in this case? It should look like this:
app.controller(currentRoute.controller, function($scope) {
$scope.pageClass = currentRoute.name;
});