angular1.x的directive
来源:互联网 发布:python 函数 传入list 编辑:程序博客网 时间:2024/06/04 23:23
转载于: http://damoqiongqiu.iteye.com/blog/1917971
学习directive
<body ng-app="app" ng-controller="MainCtrl"> <my-directive></my-directive></body>
如上图上面自定义标签是无效的。我们要自定义它
指令的作用:实现语义化标签
template && restrict
<script type="text/javascript"> app = angular.module('app', []); app.controller('MainCtrl', function($scope) { }); app.directive('myDirective', function() { return { restrict: 'ECMA', template: '<p> this is directive</p>' } });</script>
对于以上代码里面的标签,浏览器显然是不认识的,它唯一能做的事情就是无视这个标签。那么,为了让浏览器能够认识这个标签,我们需要使用Angular来定义一个hello指令(本质上说就是自己来把这种玩意儿替换成浏览器能识别的那些标准HTML标签)。
上面的注意点:
restrict: 指令声明方法
template: 渲染的元素
如果我们需要替换的HTML标签很长,显然不能用 拼接字符串的方式来写,这时候我们可以用templateUrl来替代template,从而可以把模板写到一个独立的HTML文件中
transclude
<my-directive> <span>这是原来的文字</span><br/> <p>这是原来的文字</p><br/> <div>这是原来的文字</div><br/> </my-directive>
<script type="text/javascript"> app = angular.module('app', []); app.controller('MainCtrl', function($scope) { }); app.directive('myDirective', function() { return { restrict: 'ECMA', transclude: true, template: '<p> this is <span ng-transclude></span> directive </p>' } });</script>
上面的注意点:
要利用这种写法需要设置transclude: true
上面可以看到 <my-directive>
还是存在的,如果不想他出现可以加replace:true
scope
当你想要写一个可重复使用的 directive,不能再依赖父 scope,这时候就需要使用隔离 scope 代替。共享 scope 可以直接共享父 scope,而隔离 scope 无法共享父scope
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title></head><body ng-app='app'> <div ng-controller='myCtrl'> <my-directive> <span>原来的文字</span></my-directive> </div></body></html><script type="text/javascript" src="js/angular-1.5.0.min.js"></script><script type="text/javascript"> var app = angular.module('app',[]); app.controller('myCtrl',['$scope', function($scope){ $scope.name = 'hanker'; }]); app.directive('myDirective', function(){ return { restrict: 'ECMA', template: '<p>xxxxx {{name}} xxxx<span ng-transclude></span>xxxxxxxxx</p>', transclude: true, replace: true, scope: {}, } });</script>
上面代码显示的是下图 {{name}}就没法编译成hanker
compile(编译)和link(连接)
如前所述,指令的本质其实是一个替换过程。好,既然如此,Angular到底是如何进行替换的呢?嗯嗯,这个过程分2个阶段,也就是本节标题所说的compile(编译)和link(连接)了。
阅读全文
0 0
- angular1.x的directive
- angular1.x $watch 监听的简单应用
- angular1.x 简单的全选功能
- Angular1.x规范
- Angular1.x启动分析
- angular1.x ui-route传参的三种写法
- 改变angular1.x的ajax默认数据提交类型
- angular1.x 实现表格的增删改查
- angular1.x select 常用技巧
- Angular1.x安装与配置
- angular1的使用
- Angular1
- angular1
- Angular1.3.X中embed标签使用ng-src的bug
- 搞定angular1.x——自定义指令
- 搞定angular1.x——复杂指令
- 简单实现 angular1.x 双向数据绑定
- angular1.x 指令 全选(checkbox)
- python脚本输入密码判断
- paypal在线支付演示下载PHP版
- python基础和数据类型(01,02)
- 高效率读取大文件进行数据处理-通过扩展RandomAccessFile类使之具备Buffer改善I/O性能
- 三种常见字符编码简介:ASCII、Unicode和UTF-8
- angular1.x的directive
- Python 罗马数字与阿拉伯数字的转换
- [杂题] Ural 1961. Cantonese Dialect
- 斐波那契数列的性质
- 安卓开发进阶之弹性布局FlexboxLayout--Part1(翻译)
- sql 基础知识
- 根据文本内容的长度动态的设置TextView的高度
- Java多线程与并发学习之(四):线程常用方法
- 综合实战:生产者与消费者(利用Object类解决重复操作)