angularjs 学习 指令学习一

来源:互联网 发布:python多线程selenium 编辑:程序博客网 时间:2024/05/21 10:23

指令(directive)

指令是AngularJs自定义的HTML元素或属性;

一个简单的指令定义方法如下:
angular.module('app').directive('directiveName',function(){    return {        restrict:'E',        template:string,    };})

该方法定义了一个名为directiveName的指令,该指令作为html中元素方式存在, 以<directive></directive>调用指令
当然,上述方法只是一个简单的指令定义方法,复杂的指令需要指令中其它属性的配合;

完整的创建指令的伪代码为
    angular.module('app').directive('directiveName',function(){    return {        restrict:'E',        priority:number,        template:string,        templateUrl:string,        replace:bool,        transclude:bool,        scope:bool or object,        controller:function($scope,$element,$attr,$transclude)        require:string,        link:function postLink(scope,iElement,iAttrs){...},        compile:function compile(tElement,tAttrs,transclude){            return {                pre:function preLink(scope,iElement,iAttrs,controller){...},                post:function postLink(scope,iElement,iAttrs,controller){...}            }        }    };})
详细解释
  1. restrict:描述了指令作为元素名称、元素属性或样式存在,可选值为
    E 元素 <directive></directive>
    A 属性 <div directive=""></div>
    C 样式类 <directive class=directive></directive>
    三者可以组合

  2. priority:描述了指令的优先级,大的优先级会先运行,优先级相同的指令,按照其定义的顺序执行

  3. terminal: 停止运行比该优先级还低的指令,但相同优先级的指令仍会运行
.directive('helloWorld',function(){         return {                 restrict:'EA',                 template:'<div>hello world</div>',                 priority:100,                 terminal:true     } })     .directive('helloTwo',function(){         return {             restrict:'EA',             template:'<div>JunJunDaXia</div>',             priority:120,             terminal:true         }     }) ``` helloTwo 指令会覆盖 helloWorld指令4. template: 模板会替代指令包裹的内容5. templateUrl:加载服务器上的模板6. replace: 默认为false,模板会帮当做子元素插入到此指令的元素内部;如果为true,则模板替换指令所在位置```javascript    angular.module('app').directive('helloWorld',function(){        return {            restrict:'E',            template:<div>hello world</div>,            replace:true        };    })<div class="se-preview-section-delimiter"></div>

替换后的Html为
<div>hello world</div>
如果 repalce为false,则替换后的HTML为
<hello-world><div>hello world</div></hello-world>

  1. transclude: 此属性为ture时,指令会删除原来的内容,如果模板中使用了ng-transclude指令,则删除的内容会被重新插入
 <div hello-world>123</div>.directive('helloWorld',function(){        return {                restrict:'EA',                template:'<div>hello world <span ng-transclude></span> </div>',                transclude:true,    }})<div class="se-preview-section-delimiter"></div>

解析后的html为:

<div hello-world=""><div>hello world <span ng-transclude=""><span class="ng-scope">123</span></span> </div></div>
0 0