Sachin Karia Sachin Karia - 23 days ago 12x
AngularJS Question

AngularJS ui-router with templateProvider for A/B testing not rendering templates

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) {
.state('home', {
url: '/',
templateProvider: function(testService) {
var result = testService.pick('a', 'b');
return '<div ng-include="\'app/home-' + result + '.html\'"></div>';

My index.html is below:

<title>Get Penta</title>
<script src=""></script>
<script src=""></script>
<script src="app.js"></script>
<body ng-app="myApp">

and my views

<div>Version A</div>


<div>Version B</div>

However none of the templates are rendered.


According to this article:

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';