http://www.codelord.net/2015/05/19/angularjs-dynamically-loading-directives/

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

AngularJS: Dynamically loading directives

May 19th, 2015 | Comments

It’s hard to write a webapp today without some sort of dynamic feed/list: Facebook’s news feed has photos, text statuses, ads, Twitter’s feed has promoted tweets, image tweets, retweets, and maybe you have a chat/messaging feed in your app with text, videos, photos and stickers.

While this is relatively common, it might not be straightforward to do so in Angular, or what is the Right Way™ for doing this.

The problem

Say that we get from a REST API a list of feed items, that look somewhat like this:

 
[
{
"type": "text",
"body": "hello"
},
{
"type": "image",
"url": "http://..."
}
]

Naively, we might say what we really want is to create 2 directives, one for rendering text items (text-feed-item) and one for images (image-feed-item), and write something that looks like this:

 
<div {{item.type}}-feed-item item=“item”></div>

Of course, this isn’t valid Angular code. So what should you do?

Keep it simple, stupid!

One of my main rules of thumb is to keep away from complexity as much as I can and be explicit. This means that if I have only a handful of different item directives to choose from, I’ll write something very explicit, like this:

 
<div ng-switch=“item.type”>
<div ng-switch-when="text" text-feed-item item="item"></div>
<div ng-switch-when="image" image-feed-item item="item"></div>
</div>

This has the several advantages:

  • Simple as can be
  • Explicit
  • Easily searchable (say, if you want to find who uses the image-feed-itemdirective you can use plain search and find this)

But, in case you have more than a handful of different feed item types this might get out of hand or just plain get annoying.

$compile

Angular’s way of dynamically adding directives to the DOM is compiling them. I know the word “compile” feels quite odd in our little corner of web development, but for some reason that’s the word they chose for the process of having Angular parse a DOM node and executing all the Angular goodness it requires.

Making a dynamic directive that does basically what our first naive attempt looked like isn’t that hard, once you know about Angular’s $compile service:

 
<div item-generator item="item"></div>
 
angular.module('myApp').directive('itemGenerator', function($compile) {
return {
scope: {
item: '='
},
link: function(scope, element) {
var generatedTemplate = '<div ' + scope.item.type
+ '-feed-item item="item"></div>';
element.append($compile(generatedTemplate)(scope));
}
};
});

This will result in something that looks like this if you inspect the DOM:

 
<div item-generator item="item">
<div image-feed-item item=“item”>
<img ...>
</div>
</div>

As you can see, $compile has two steps. First, we call it with the HTML we want to generate, which returns a function. We then call that function with the specific scope we want the generated element to have and then we actually get the new element that we can add to the DOM.

Yes, this is more complicated, requires being more comfortable with how Angular works and doesn’t have the benefits I listed above for the simpler solution, but sometimes this approach is necessary.

最新文章

  1. Could not load type &#39;System.Web.Mvc.ViewPage&lt;dynamic&gt;&#39; in asp.net mvc2 after publishing the website
  2. LinuxMint 17.1 Cinnamon桌面窗口焦点bug
  3. ios数据库常用sql语句
  4. hdu3847Trash Removal(凸包)
  5. net core 实战之 redis 负载均衡和&quot;高可用&quot;实现
  6. 【温故知新】c#异步编程模型(APM)--使用委托进行异步编程
  7. CSS之生成全屏背景图片
  8. uCOS-II任务的挂起和恢复
  9. Debug调试
  10. Android 项目建立步骤
  11. 纯 CSS 创建各种不同的图形形状
  12. 如何制作一个类似Tiny Wings的游戏 Cocos2d-x 2.1.4
  13. MySQL向数据库表的某字段追加数据
  14. Illegal invocation with document.querySelector [duplicate]
  15. c#重命名文件,报错“System.NotSupportedException”类型的未经处理的异常在 mscorlib.dll 中发生”
  16. Saving custom fields in production order
  17. Python变量和简单数据类型
  18. I/O复用之epoll
  19. rbac之 权限粒度控制到按钮级别
  20. Pycharm及python安装详细教程

热门文章

  1. java 复习整理(二 数据类型和几种变量)
  2. python module :shelve
  3. [bzoj4514][SDOI2016]数字配对——二分图
  4. 无线网络发射器选址 (NOIP2014)(真&#183;纯模拟)
  5. openGL深度缓冲区问题
  6. 【计算机网络】简单网络管理协议 SNMP
  7. python的tips:字符和字符串的问题
  8. js正则常用的一些东西
  9. 51nod 1062 序列中最大的数【打表】
  10. Python与数据结构[1] -&gt; 栈/Stack[0] -&gt; 链表栈与数组栈的 Python 实现