0

I have created an angular app where I would like to randomly render two different homepage view when a user accesses the url.

I have created the app.js file with the following code using templateProvider to inject the testService which carries a pick function to return random selection of two arguments. This is below:

var myApp = angular.module('myApp', ['ui.router']);

myApp.service('testService', function(){
  function pick() {
    var i = Math.floor(Math.random() * arguments.length);
    return arguments[i];
  }
});


myApp.config(['$stateProvider','$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
  $stateProvider
  .state('home', {
    url: '/',
    templateProvider: function(testService) {
      var result = testService.pick('a', 'b');
      return '<div ng-include="\'app/home-' + result + '.html\'"></div>';
    }
  });
  $urlRouterProvider.otherwise('/');
}])

My index.html is below:

<html>
<head>
  <title>Get Penta</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
  <script src="https://unpkg.com/angular-ui-router/release/angular-ui-router.min.js"></script>
  <script src="app.js"></script>
</head>
<body ng-app="myApp">
  <ui-view></ui-view>
</body>
</html>

and my views home-a:

<div>Version A</div>

home-b:

<div>Version B</div>

However none of the templates are rendered.

Sachin Karia
  • 547
  • 2
  • 8
  • 22

1 Answers1

1

According to this article: https://github.com/angular-ui/ui-router/wiki

You can do this in several ways. I think your use of ng-include is failing, because basically this is done at page load time, and it's too late for that. I think a simple solution is to use the templateUrl, like this:

$stateProvider.state('home', {
    templateUrl: function() {
      function pick(){
          var i = Math.floor(Math.random() * arguments.length);
          return arguments[i];
      }
      var result = pick('a', 'b');
      return 'app/home-' + result + '.html';
    }
})
Mikkel
  • 7,693
  • 3
  • 17
  • 31