发表于: 2017-06-30 22:43:27

1 982


今天完成的事情:

主要学习自定义指令的用法。


指令在框架中的执行流程:

1.浏览器得到 HTML 字符串内容,解析得到 DOM 结构。

2.ng 引入,把 DOM 结构扔给 $compile 函数处理:

    ①   找出 DOM 结构中有变量占位符

    ②   匹配找出 DOM 中包含的所有指令引用

    ③   把指令关联到 DOM

    ④   关联到 DOM 的多个指令按权重排列

    ⑤   执行指令中的 compile 函数(改变 DOM 结构,返回 link 函数)

    ⑥   得到的所有 link 函数组成一个列表作为 $compile 函数的返回

3. 执行 link 函数(连接模板的 scope)。


指令命名时用驼峰规则,使用时用-分割各单词。

指令的参数如下:

myModule.directive('namespaceDirectiveName', function factory(injectables) {

   var directiveDefinitionObject = {
       restrict: string,//指令的使用方式,包括标签,属性,类,注释
       priority: number,//指令执行的优先级
       template: string,//指令使用的模板,用HTML字符串的形式表示
       templateUrl: string,//从指定的url地址加载模板
       replace: bool,//是否用模板替换当前元素,若为false,则append在当前元素上
       transclude: bool,//是否将当前元素的内容转移到模板中
       scope: bool or object,//指定指令的作用域
       controller: function controllerConstructor($scope, $element, $attrs, $transclude) {...
},//定义与其他指令进行交互的接口函数
       require: string,//指定需要依赖的其他指令
       link: function postLink(scope, iElement, iAttrs) {...
},//以编程的方式操作DOM,包括添加监听器等
       compile: function compile(tElement, tAttrs, transclude) {
           return:{
               pre: function preLink(scope, iElement, iAttrs, controller) {...
},
post: function postLink(scope, iElement, iAttrs, controller) {...
}
           }
       }//编程的方式修改DOM模板的副本,可以返回链接函数
   };

   return directiveDefinitionObject;
});


解释一下常用的属性:

1.template或templateUrl,模板内容或模板链接。可将模板文件写入如下标签中并放在自定义指令文件头部,然后通过templateUrl来引用,减少http请求。

<script type="text/ng-template" id="helloTemplate.html">
   <div>hello</div>
</script>


2.restrict ,值可为E,A,C,M或结合使用, 默认值为 EA,意义和形式如下:

E 标签 <my-menu title=Products></my-menu>

A 属性 <div my-menu=Products></div>

C 类 <div class="my-menu":Products></div>

M 注释 <!--directive:my-menu Products-->

此属性加载模板template中的信息。指令元素中内容如何加入了内容,加入的内容默认不会显示。

如<div my-menu=Products>abcd</div>中,abcd不会显示。


3.replace,默认为false。

当使用<my-menu></my-menu>时,DOM中生成的文件为

<my-menu>
   模板文件
</my-menu>

replace设为true,可消除外围my-menu标签。


4.transclude,默认为false。使用如下:

app.directive('sayHello',function(){
   return {
       restrict : 'E',
template : '<div>hello<b ng-transclude></b></div>',
transclude : true
   };
})

html中写入<say-hello>美女</say-hello>,DOM输出为:

<say-hello>
   <div>hello<b>美女</b></div>
</say-hello>


明天计划的事情:

继续学习属性,尝试写插件。


遇到的问题:

对于restrict:"M"属性应用不成功,不知是什么原因。


收获:

如上。


返回列表 返回列表
评论

    分享到