码迷,mamicode.com
首页 > Web开发 > 详细

AngularJs-指令1

时间:2015-01-25 16:33:58      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:

前言:

  前面写的有些乱,并且有些罗嗦,以后会注意的。希望我写的文章能帮助大家。

1,什么是指令

  简单的说,指令是angularjs在html页面中建立一套自己能识别的标签元素、属性、类和注释,用来达到功能复用的目的。

2,创建指令

<!DOCTYPE html>
<html ng-app="MyModule">
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
    <!-- 指令的第一种模式 E -->
    <hello></hello>
    
    <!-- 指令的第二种模式 A -->
    <div hello></div>
    
    <!-- 指令的第三种模式 C -->
    <div class="hello"></div>
    
    <!-- 指令的第四种模式 M-->

    <!-- directive:hello -->
    <div></div>

    <script src="js/angular-1.3.0.js"></script>
    <script src="js/hello.js"></script>
</body>
</html>

 从上面的代码可以看出,指令有四种创建方式,上面的四种模式对应下面js代码中 restrict属性AEMC。

var myModule = angular.module("MyModule",[]);

//创建指令 myModule.directive(
‘hello‘,function(){ return{ restrict:‘AEMC‘, // 匹配模式 A:属性 E:元素 M:注释 C:Class template:‘<div>hello world</div>‘, replace:true } })

可以自己动手创建。

3,指令--restrict

 restrict意思是约束,限定的意思,在此就是限定这个指令可用的四种匹配模式。

 这么多模式,我们该在什么场景下用呢?

  •    A:属性指令,如果想在已有的标签再添加指令,推荐使用这个方式。
  •    E:元素指令,官方推荐属性,可以自定义标签显示。
  •    M:注释指令,一般不使用,容易删除。别人不好理解。
  •    C:样式类指令,一般不使用,容易误解。

4,指令--template

  模板(代码片段)的使用我们有4中方式。

  •   template:‘<div>hello world</div>‘,把代码片段直接复制给模板属性
  •       templateUrl:‘tmpl/hello.html‘,引用外部文件,当你的模板有很多代码的时候使用。
  •       template:$templateCache.get(‘hello.html‘),使用模板缓存,这个方法解决一个模板复用的情况,hello.html是一个虚拟的文件,可不建立
  •       模板可以为空,直接在 html文件里面写 <hello>hello</hello>

 

// 注射器加载所有模块时,此方法执行一次,缓存模板
myModule.run(function($templateCache){
    // console.log("323"); html文件是虚拟的,可以任意起名字
    $templateCache.put(‘hellos.html‘,"<div>hello everyone..</div>")
})
myModule.directive(‘hello‘,function($templateCache){
    return{
        restrict:‘AECM‘,
        template:$templateCache.get(‘hellos.html‘),
        replace:true
    }
})

 

5,指令--replace

  replace意思替换,代替的意思。如果进行指令嵌套的时候,需要改变下。

html:

    <hello>
        <div>nihao</div>
    </hello>

js:

myModule.directive(‘hello‘,function(){
    return{
        restrict:‘AE‘,
        transclude:true,
        template:‘<div>hello everyone <div ng-transclude></div></div>‘,
    }
})

在这里使用了 ng-transclude 方法,这个方法的作用是让angularjs把指令嵌套的内容放到 带有ng-transclude属性的标签中去。

技术分享

6,指令--compile(编译阶段)

angularjs默认的函数,我们可以自定义该函数,当指令dome变化完毕就会执行。

7,指令--link(链接阶段)

在link函数里面可以给元素绑定事件。

8,总结

  关于指令的其他属性和方法,需要大家到官网去找自己看。我这边也会把这节代码上传到我的github(https://github.com/NIKing/angularJs.git)上。

 

  

AngularJs-指令1

标签:

原文地址:http://www.cnblogs.com/zhiyuan-2011/p/4248358.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!