0

The AngularJS application uses the ui-router. There are two types of pages:

  1. Routes specified explicitly in routes.js
  2. Routes derived dynamically on demand

When the page loads the application makes a request for data (type, variables). How to load a template and the controller of the page based on its type?

/**
There is an option with this routing, but then it will not work the other routed to specified explicitly
*/
/* routes.js */
// definition of "page" state

/* PageController.js */
// getting type of page
$scope.type = res.data.type;

/* page.jade */
div(ng-if=«page.type == ‘index’»)
    div(ng-controller=‘IndexController’)
div(ng-if=«page.type == ‘catalog’»)
    div(ng-controller=‘IndexController’)

It is not clear how to load templates, and there is the question of the performance of this solution. Perhaps there is a better solution?

laser
  • 1,388
  • 13
  • 14

1 Answers1

0

In your IndexController, put your logic to fetch the page you want to display. Then store this information into the scope.

In you view use ngIf and ngInclude to load your templates depending of you variable value.

Check the example bellow.

routes.js

angular.module('yourApp', ['ngRoute', ...])
    .config(function($routeProvider){
        $routeProvider
            .when('/', {
                templateUrl: 'template0.html',
                controller: 'IndexController'
            });
    });

template0.html

<div ng-if="page.type == 'index'">
  <div ng-include="template1.html"> ... </div>
</div>
<div ng-if="page.type == 'catalog'">
  <div ng-include="template2.html"> ... </div>
</div>

In both cases your controller will already be loaded for the template0.html.

Thomas Kerbrat
  • 106
  • 1
  • 7
  • If the partials views are pre-loaded, using ng-include is negligible in term of performance hits. Take a look at this answer: [angularjs / rendering Performance difference between inlining or using ng-include](http://stackoverflow.com/questions/16621995/angularjs-rendering-performance-difference-between-inlining-or-using-ng-includ). – Thomas Kerbrat Nov 13 '15 at 16:13