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

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

我创建了一个 angular 应用程序,我想在用户访问 url.

时随机呈现两个不同的主页视图

我创建了 app.js 文件,其中包含以下代码,使用 templateProvider 将带有 pick 函数的 testService 注入 return 随机选择两个参数。下面是:

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('/');
}])

我的index.html如下:

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

和我的看法 主页-a:

<div>Version A</div>

home-b:

<div>Version B</div>

然而 none 个模板已呈现。

根据这篇文章:https://github.com/angular-ui/ui-router/wiki

您可以通过多种方式做到这一点。我认为您对 ng-include 的使用失败了,因为基本上这是在页面加载时完成的,而且为时已晚。我认为一个简单的解决方案是使用 templateUrl,如下所示:

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