LeoYuan / leoyuan.github.io

This is my blog repo.
http://leoyuan.github.io
17 stars 2 forks source link

使用NodeJS来完成AngularJS自定义标签的预编译功能 #9

Open LeoYuan opened 11 years ago

LeoYuan commented 11 years ago

  相信使用过AngularJS的都知道它的强大,包括MV双向的数据绑定、Dependency Injection和测试功能,当然还包括本文将要描述的自定义标签的功能,即可通过angular的directive方法定义自定义标签,在DOM加载完后会调用directive的compile/link函数对自定义标签进行解析,生成任意你想要DOM结构,如<my:tree data-model="someModel" [other attrs]></my:tree>,即可生成一棵树的模样,特别声明:该过程是纯前端,是不是很屌?

  不过该过程需要在browser的环境下,因为需要提供BOM对象window, document,是不是就没辙了呢?No, 有解决方案,NodeJS中有一个模块叫jsdom,是使用纯js产生BOM对象的工具。

  好吧,前戏做的差不多了,进正题吧。

  第一步,改造angular --- nodejs模块化+去立即函数。将angular的外围立即函数改造成一个普通函数,命名为getAngular,即将原代码

(function(window, document, undefined) {
    // angular code
})(window, document);

改成

function getAngular(window, document) {
     // angular code
    return angular;
}
exports.getAngular = getAngular;

  第二步,准备你想要预编译的页面,假设为test.ang,内容如下:

<my:html>
    <my:head></my:head>
    <my:body></my:body>   
</my:html>

  第三步,写上述三个扩展标签的compile/link方法,具体方法不在此赘述,详细请参见:Angular Directive

  第四步,使用jsdom来生成window, document等BOM对象,具体代码如下:

var jsdom = require("jsdom"),
    fs = require("fs"),
    angular = require("angular").getAngular();
jsdom.env({
  html: "./test.ang",
  done: function (errors, window) {
     var doc = window.document;
     angular.bootstrap(doc, ["angMod1", "angMod2"]);
     fs.writeFileSync("test.html", doc.outerHTML, "UTF-8");
  }
});

  这时,假如一切顺利的话,在test.html已经能看到你想要的效果了,可以像下边这样,

<!doctype html>
<html>
<head>
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 
  <script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
  <!-- some css files -->
</head>
<body>
  Hello, AngularJS + NodeJS!
</body>
</html>

  当然想做成啥样,纯碎取决于你的需求了^_^。

  注:本文大部分思想源自@黄智大哥 --- 一个对技术有着执着的追求的人。