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.

AngularJS: Dynamically loading directives的更多相关文章

  1. Dynamically loading an external JavaScript or CSS file

    原文:   Dynamically loading an external JavaScript or CSS file 通过javascript动态加载css文件和javascript文件,主要是通 ...

  2. [AngularJS] Lazy loading Angular modules with ocLazyLoad

    With the ocLazyLoad you can load AngularJS modules on demand. This is very handy for runtime loading ...

  3. [AngularJS + Webpack] require directives

    direictives/index.js: module.exports = function(ngModule) { //register all the directives here requi ...

  4. AngularJS 指令(Directives)实践指南

    指令(Directives)是所有AngularJS应用最重要的部分.尽管AngularJS已经提供了非常丰富的指令,但还是经常需要创建应用特定的指令.这篇教程会为你讲述如何自定义指令,以及介绍如何在 ...

  5. AngularJs中的directives(指令part1)

    一.指令的职责   指令的职责是修改DOM结构,并将作用域和DOM连接起来.即指令既要操作DOM,将作用域内的数据绑定到DOM节点上,又要为DOM绑定事件调用作用域内的对应的方法. 二.创建自定义指令 ...

  6. AngularJS自定义指令(Directives)在IE8下的一个坑

    在项目中,由于要兼容到IE8,我使用1.2.8版本的angularJS.这个版本是支持自定义指令的.我打算使用自定义指令将顶部的header从其他页面分离.也就是实现在需要header的页面只用在&l ...

  7. [AngularJS] Lazy Loading modules with ui-router and ocLazyLoad

    We've looked at lazy loading with ocLazyLoad previously, but what if we are using ui-router and want ...

  8. Dynamically loading unmanaged OCX in C#

    You'll have to perform a number of steps that are normally taken of automatically when you use the t ...

  9. AngularJS之directive

    AngularJS之directive AngularJS是什么就不多舌了,这里简单介绍下directive.内容基本上是读书笔记,所以如果你看过<AngularJS up and runnin ...

随机推荐

  1. Tomcat学习笔记(八)

    Tomcat载入器(二) Tomcat拥有不同的自定义类加载器,以实现对各种资源库的控制. 1.同一个web服务器里,各个web项目之间各自使用的java类库要互相隔离.  2.同一个web服务器里, ...

  2. server reached pm.max_children setting (5), consider raising it

    先查看日志 /data1/server/php-cgi/var/log/php-fpm.log[19-Dec-2012 11:41:13] WARNING: [pool www] server rea ...

  3. CodeVs1515 跳

    题目描述 Description 邪教喜欢在各种各样空间内跳. 现在,邪教来到了一个二维平面.在这个平面内,如果邪教当前跳到了(x,y),那么他下一步可以选择跳到以下4个点:(x-1,y), (x+1 ...

  4. 【CF1023D】Array Restoration(构造,线段树)

    题意:有一个长为n的序列,对其进行q次操作,第i次操作可以把连续的一段覆盖为i 现在给出操作后的序列,第i个数字为a[i],其中有一些为0的位置可以为任意值,要求构造任意一组合法的操作后的序列 无解输 ...

  5. 行为型设计模式之模板方法(Template Method)

    结构 意图 定义一个操作中的算法的骨架,而将一些步骤延迟到子类中.Te m p l a t e M e t h o d 使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤. 适用性 一次性 ...

  6. linux内核分析之进程地址空间【转】

    转自:http://blog.csdn.net/bullbat/article/details/7106094 版权声明:本文为博主原创文章,未经博主允许不得转载. 本文主要介绍linux内核中进程地 ...

  7. MongoDB中$redact操作符的使用

    介绍 redact <- redaction 修订/校验,意思是对文档内容进行过滤,选择一些过滤或保留的信息 . access level 存取等级 有三种: - $$DESCEND 返回当前等 ...

  8. IFC and BFC

    BFC and IFC 1,IFC -- 针对行内元素 -- 行内格式上下文 BFC --针对块级元素 -- 块级格式上下文 2,IFC特点: 行框的高度由包含元素的高度和有没有float元素决定. ...

  9. 【C语言】复杂类型声明

    原文地址: http://blog.csdn.net/wangweixaut061/article/details/6549768 原文不让转载,但实在是有用,就拷贝了一小部分过来.全文请点开链接. ...

  10. iOS手势UIGestureRecognizer的使用失效问题

    问题:视图正常展示在界面中,父层是放在window上的,底部的一个控件的点击事件失效(所有设置都正常) 解决思路:虽然视图能够正常展示,但是发现父类视图的底部尺寸比子类的视图的尺寸小,也就是说上层视图 ...