Sachin Karia Sachin Karia - 2 months ago 32
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) {
$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.

Answer

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';
    }
})
Comments