原文:http://davidcai.github.io/blog/posts/router-dynamic-templates/

ui-router : templateProvider vs template

----------------------------------------------

Router: Dynamic Templates

Sat Aug 15, 2015

This post discusses how to create dynamic templates by leveraging the templateProvider configuration provided by Angular’s built-in router or the third-party UI Router.

PROBLEM

For Single Page Applications (SPAs), we often need to switch views or states inside containers. This is usually done through routers. With either Angular’s built-in router or the popular UI Router, we are able to define the relationship between states and their templates. For instance, here we defined a state home and its template URL app/home/home.html:

app.config(function($stateProvider) {
$stateProvider.state('home', {
url: '/',
templateUrl: 'app/home/home.html'
});
});

In some cases, this state-to-template relationship can not be determined beforehand at the config time. The decision of what the template or template URL will be used for a state has to wait for the availability of run-time data. For example:

  • User’s account type, e.g. show Home version A for members, and version B for public users.
  • A/B testing, e.g. a A/B testing service randomly picks from two versions – A or B.

In either scenario, the template cannot be fixed to app/home/home.html, and has be to resolved using run-time data.

Router’s templateUrl configuration accepts a function which can be used to create dynamic template URL. However, we are not able to inject run-time dependencies (e.g. user services, or A/B test services) into the templateUrl function. The only available argument of the templateUrl function is $stateParams.

$stateProvider.state('home', {
templateUrl: function($stateParams) { // Can not inject dependencies
return 'app/home.' + $stateParams.option + '.html';
}
});

SOLUTION

The answer is templateProvider.

Both Angular built-in router and the UI Router have a templateProvider configuration. templateProvider accepts a function that can be injected with run-time dependencies.

$stateProvider.state('home', {
templateProvider: function(abTestService) { // abTestService is injected here
var result = abTestService.pick('a', 'b'); // Choose version A or B
return '...'; // Return template content based on the result
}
});

templateProvider returns template content (not an URL to the template). We can certainly embed HTML markups directly in JavaScript, but for complicate HTML, it’s better to externalize the HTML content to separate template files. Here, we created home-a.html and home-b.html, and ngInclude them in the templateProvider function:

<!-- Home version A at app/home/home-a.html -->
<div ng-controller="HomeAController">Version A</div> <!-- Home version B at app/home/home-b.html -->
<div ng-controller="HomeBController">Version B</div>
$stateProvider.state('home', {
templateProvider: function(abTestService) {
var result = abTestService.pick('a', 'b'); // ngInclude template content based on the A/B test result
return '<div ng-include="\'app/home/home-' + result + '.html\'"></div>';
}
});

templateProvider can also return a Promise which is resolved to template content.

$stateProvider.state('home', {
templateProvider: function($http, USER_SERVICE_REST_URL) { // Here, we return a promise instead of the template content
return $http.get(USER_SERVICE_REST_URL).then(function(data) {
var result = (data.type === 'member' ? 'a' : 'b'); // Return the template content
return '<div ng-include="\'app/home/home-' + result + '.html\'"></div>';
});
}
});

EVEN BETTER SOLUTION

Having ngInclude in templateProvider function feels still a bit hackish to me. The ideal solution is to specify a template URL, and then let Angular fetch the content. However, sending separate HTTP requests just to fetch templates seems to be unnecessary web traffic. It will be better if the template content can be cached in the $templateCache service; and then, all I need to do is $templateCache.get('templateUrl'):

$stateProvider.state('home', {
templateProvider: function(abTestService, $templateCache) {
var result = abTestService.pick('a', 'b'); // Retrieve the cached template content from $templateCache service
return $templateCache.get('app/home/home-' + result + '.html');
}
});

To achieve this, we need a Gulp task to convert all HTML files under the app/ directory to JavaScript strings, and save the strings in $templateCache.

// Load gulp and its plugins
var gulp = require('gulp');
var minifyHtml = require('gulp-minify-html');
var angularTemplateCache = require('gulp-angular-templatecache'); gulp.task('templates', function() { return cacheTemplates('src/app/**/*.html', 'app.template.js'); function cacheTemplates(input, output) {
return gulp.src(input) // Get all HTML files
.pipe(minifyHtml({ // Minify HTML content first
empty: true,
spare: true,
quotes: true
}))
.pipe(angularTemplateCache(output, { // Save minified strings to cache
module: 'myApp' // Setup $templateCache for Angular module 'myApp'
}))
.pipe(gulp.dest('.tmp/templates/')); } // /function cacheTemplates });

Then, import the generated template.js in index.html:

<script src=".tmp/templates/app.template.js"></script>

CONCLUSION

By leveraging the templateProvider function that can be injected with dependencies, we are able to resolve template content based on run-time data. This technique is useful for switching among more than one templates for a state, for instance, A/B testing, and swappable content in limited space.

angular—— Dynamic Templates的更多相关文章

  1. ES - Dynamic templates 动态模板

    1.ES Mapping 在lucene中,索引中每个字段都需要指定很多属性,例如:是否分词.采用哪个分词器.是否存储等. 在ES中,其实索引中每个字段也需要指定这些属性,我们有时候并没有对这些属性进 ...

  2. [Angular 2] Set Values on Generated Angular 2 Templates with Template Context

    Angular 2 templates have a special let syntax that allows you to define and pass a context when they ...

  3. [Angular] Dynamic component's instance and sorting

    After create a component dynamic, we are able to change the component's props and listen to its even ...

  4. [Angular] Dynamic component rendering by using *ngComponentOutlet

    Let's say you want to rending some component based on condition, for example a Tabs component. Insid ...

  5. [Angular] Dynamic components with ComponentFactoryResolver

    To create a component dynamicly. 1. Add a container with ref: @Component({ selector: 'app-root', tem ...

  6. ANGULAR 2 FOR REACT DEVELOPERS

    Now that Angular 2 is in beta, the time has come for us to drop everything and learn something new, ...

  7. [Angular 2] Create template with Params

    Angular 2 templates have a special let syntax that allows you to define and pass a context when they ...

  8. [Angular 2] Generate and Render Angular 2 Template Elements in a Component

    Angular 2 Components have templates, but you can also create templates inside of your templates usin ...

  9. [Angular 2] Rendering an Observable with the Async Pipe

    Angular 2 templates use a special Async pipe to be able to render out Observables. This lesson cover ...

随机推荐

  1. camera驱动框架分析(中)

    camera host的驱动 下面开始分析camera host吧,如果仅仅是想知道camera sensor驱动怎么写,而不想知道内部具体怎么个调用流程,怎么个架构设计,那可以跳过该部分,直接去看i ...

  2. Java坦克大战 (四) 之子弹的产生

    本文来自:小易博客专栏.转载请注明出处:http://blog.csdn.net/oldinaction 在此小易将坦克大战这个项目分为几个版本,以此对J2SE的知识进行回顾和总结,希望这样也能给刚学 ...

  3. zabbix ZBX_NOTSUPPORTED: Timeout while executing a shell script.

    有一个监控一直都是正常的,今天突然收到报警邮件,上服务器查看服务又是正常的,但是报警邮件还是没恢复 监控端进行脚本测试,发现是正常的 到监控端使用zabbix_get -s ip -p 端口  -k ...

  4. python中的闭包与装饰器

    #原创,转载请留言联系 装饰器的本质就是闭包,所以想知道装饰器是什么,首先要理解一下什么是闭包. 闭包 1. 外部函数返回内部函数的引用.2. 内部函数使用外部函数的变量或者参数. def outer ...

  5. String、ANSIString、PChar及TBytes之间的转换 BytesOf move stringof

    一.string转为ansistring 1.直接赋值 (有警告)2.ansistring()类型强制转换.(无警告) 二.ansistring 转为string 1.直接赋值 (有警告)2.stri ...

  6. Redis安装-CentOs7

    官方地址 确保gcc已经安装 $ yum list installed | grep gcc $ yum install gcc 下载.提取和编辑Redis: $ wget http://downlo ...

  7. python-函数(命名空间、作用域、闭包)

    一.命名空间 全局命名空间 局部命名空间 内置命名空间 *内置命名空间中存放了python解释器为我们提供的名字:input,print,str,list,tuple...它们都是我们熟悉的,拿过来就 ...

  8. poj 2007(凸包)

    Scrambled Polygon Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 8005   Accepted: 3798 ...

  9. Laravel跳转回之前页面,并携带错误信息

    用Laravel5.1开发项目的时候,经常碰到需要携带错误信息到上一个页面,开发web后台的时候尤其强烈. 直接上: 方法一:跳转到指定路由,并携带错误信息 return redirect('/adm ...

  10. PHP文件操作函数

    1 获得文件名: basename(); 给出一个包含有指向一个文件的全路径的字符串,本函数返回基本的文件名.如果文件名是以 suffix 结束的,那这一部分也会被去掉. eg: 复制代码 代码如下: ...