Angular.JS中的指令引用template与指令当做属性详解


Posted in Javascript onMarch 30, 2017

一、引用template

对于指令,可以把它简单的理解成在特定DOM元素上运行的函数,指令可以扩展这个元素的功能。

指令要生效,那么html头里面要

<html lang="en" ng-app="app">

制定ng-app的值和定义指令的module名字一致:

angular.module('app',[])

指令的完整参数:

angular.module('myApp', [])
.directive('myDirective', function() {
 return {
 restrict: String,
 priority: Number,
 terminal: Boolean,
 template: String or Template Function:
 function(tElement, tAttrs) {...},
 templateUrl: String,
 replace: Boolean or String,
 scope: Boolean or Object,
 transclude: Boolean,
 controller: String or
 function(scope, element, attrs, transclude, otherInjectables) { ... },
 controllerAs: String,
 require: String,
 link: function(scope, iElement, iAttrs) { ... },
 compile: // 返回一个对象或连接函数,如下所示: function(tElement, tAttrs, transclude) {
 return {
 pre: function(scope, iElement, iAttrs, controller) { ... },
 post: function(scope, iElement, iAttrs, controller) { ... }
 }
 return function postLink(...) { ... }
 }
 };
 });

指令可以使用的方式:

restrict[string]

restrict是一个可选的参数。用于指定该指令在DOM中以何种形式被声明。默认值是A,即以属性的形式来进行声明。

可选值如下:

  • E(元素)<my-directive></my-directive>
  • A(属性,默认值)<div my-directive="expression"></div>
  • C(类名)<div class="my-directive:expression;"></div>
  • M(注释)<--directive:my-directive expression-->

replace[bool]

replace是一个可选参数,如果设置了这个参数,值必须为true,因为默认值为false。默认值意味着模板会被当作子元素插入到调用此指令的元素内部,

例如上面的示例默认值情况下,生成的html代码如下:

<my-directive value="http://www.baidu.com" text="百度"><a href="http://www.baidu.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" >百度</a></my-directive>

如果设置replace=true

<a href="http://www.baidu.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" value="http://www.baidu.com" text="百度">百度</a>

据我观察,这种效果只有设置restrict="E"的情况下,才会表现出实际效果。

template[string or function]

template参数是可选的,必须被设置为以下两种形式之一:

 一段HTML文本;

一个可以接受两个参数的函数,参数为tElement和tAttrs,并返回一个代表模板的字符串。tElement和tAttrs中的t代表template,是相对于instance的。

不管是返回html文本还是函数,都是最后替换一个html,和replace属性搭配使用的,先给出一个完整的index.heml directive.js,以这个为例子来说明:

<!doctype html>
<html lang="en" ng-app="app">

<head>
 <meta charset="utf-8">
 <title>My HTML File</title>
 <link rel="stylesheet" href="bootstrap/css/bootstrap.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
 <script src="angularjs/angular.js"></script>
 <script src="mydirective.js"></script>
</head>

<body>
 <my-directive></my-directive>
</body>

</html>

然后js:

angular.module('app',[])
 .directive('myDirective', function () {
 return {
 restrict: 'E',
 template: '<a href="http://www.baidu.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" >百度</a>'
 };
 })

最后的运行效果以及firebug查看到的效果:

Angular.JS中的指令引用template与指令当做属性详解

如果添加指令的replace属性为ture,那么就不会有这个directvie指令部分了:

Angular.JS中的指令引用template与指令当做属性详解

上面就是差别。

再说说指令定义里面模板参数是函数的情况,我们改写html以及js:

<!doctype html>
<html lang="en" ng-app="app">

<head>
 <meta charset="utf-8">
 <title>My HTML File</title>
 <link rel="stylesheet" href="bootstrap/css/bootstrap.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
 <script src="angularjs/angular.js"></script>
 <script src="mydirective.js"></script>
</head>

<body>
 <my-directive value="http://www.baidu.com" text="百度"></my-directive>
</body>

</html>

js文件:
angular.module('app',[])
 .directive('myDirective', function () {
 return {
 restrict: 'EAC',
 template: function (elem, attr) {
  return "<a href='" + attr.value + "'>" + attr.text + "</a>";
 }
 };
 })

指令定义的template是一个函数对象,返回一个html的字符串,那么他的elem和attr就是分别代表这个指令和他在index.html里面的属性:

attr.value和attr.text分别对应:

<my-directive value="http://www.baidu.com" text="百度"></my-directive>

里面的value和text。

不replace的情况:

Angular.JS中的指令引用template与指令当做属性详解

二、指令当做属性

上面说过:

angular.module('myApp', []) 
 .directive('myDirective', function() { 
 return { 
 restrict: String, 后面省略

指令restrict有四种用法,默认是A,也就是当做属性,

  • E(元素)<my-directive></my-directive>
  • A(属性,默认值)<div my-directive="expression"></div>
  • C(类名)<div class="my-directive:expression;"></div>
  • M(注释)<--directive:my-directive expression-->

然后如果一个指令直接返回一个函数的时候,其实返回的一个link函数,比如:

angular.module('time', [])
 .directive('xxx', function() {
 return function(scope, element, attrs) {

这个是表示直接link。

当指令做属性的时候,有两重含义:

      1.在一个html元素里面制定为属性

      2.js定义的指令名。

看一个例子:

JS:

angular.module('time', [])
 .controller("Ctrl2", function($scope) {
 $scope.format = 'M/d/yy h:mm:ss a';
 })
 // Register the 'myCurrentTime' directive factory method.
 // We inject $timeout and dateFilter service since the factory method is DI.
 .directive('myCurrentTime', function($timeout, dateFilter) {
 // return the directive link function. (compile function not needed)
 return function(scope, element, attrs) {
  var format, // date format
  timeoutId; // timeoutId, so that we can cancel the time updates

  // used to update the UI
  function updateTime() {
  element.text(dateFilter(new Date(), format));
  }

  // watch the expression, and update the UI on change.
  scope.$watch(attrs.myCurrentTime, function(value) {
  format = value;
  updateTime();
  });

  // schedule update in one second
  function updateLater() {
  // save the timeoutId for canceling
  timeoutId = $timeout(function() {
   updateTime(); // update DOM
   updateLater(); // schedule another update
  }, 1000);
  }

  // listen on DOM destroy (removal) event, and cancel the next UI update
  // to prevent updating time ofter the DOM element was removed.
  element.bind('$destroy', function() {
  $timeout.cancel(timeoutId);
  });

  updateLater(); // kick off the UI update process.
 }
 });

然后index.html:

<!doctype html>
<html lang="en" ng-app="time">

<head>
 <meta charset="utf-8">
 <title>My HTML File</title>
 <link rel="stylesheet" href="bootstrap/css/bootstrap.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
 <script src="angularjs/angular.js"></script>
 <script src="mydirective.js"></script>
</head>

<body>
 <div ng-controller="Ctrl2">
 Date format:
 <input ng-model="format">
 <hr/>
 Current time is: <span my-current-time="format"></span>
 </div>
</body>

</html>

注意:ng-app="time"一定要指明是time。否则无法关联起来。

分析如下:

  • 给span制定了一个属性,绑定到了scope里面的format
  • <span my-current-time="format"></span>
  • 定义了输入框,绑定了scope里面的format
  • <input ng-model="format">
  • 定义了controller -- Ctrl2, 然后引入了scope,定义了变量format
  • 定义了指令myCurrentTime , 然后就是和html里面的my-current-time="format"对应,html里面用破折号连起来,指令就是驼峰样子的myCurrentTime(首字母小写)
  • link函数的三个参数,以及attrs的使用:
    return function(scope, element, attrs) {
    scope.$watch(attrs.myCurrentTime, function(value) {
  • 可看到,myCurrentTime既是指令名字,然后在这个span元素里面又是属性名,他的值是format的真实值。
  • 用firebug看到:Angular.JS中的指令引用template与指令当做属性详解
  • 指令当成属性,不会有replace起作用的时候,不会被替换也不会插入,就是一个属性,后面的日期值,其实是updateTime()函数直接写elem.text的效果。
  • 此处指令当做属性的作用就是扩展当前元素的功能。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对三水点靠木的支持。

Javascript 相关文章推荐
JS 遮照层实现代码
Mar 31 Javascript
推荐30个新鲜出炉的精美 jQuery 效果
Mar 26 Javascript
JS实现为表格动态添加标题的方法
Mar 31 Javascript
Jquery使用小技巧汇总
Dec 29 Javascript
JavaScript 深层克隆对象详解及实例
Nov 03 Javascript
获取jqGrid中选择的行的数据
Nov 30 Javascript
AngularJS报错$apply already in progress的解决方法分析
Jan 30 Javascript
jQuery中ztree 点击文本框弹出下拉框的实例代码
Feb 05 Javascript
jquery.uploadifive插件怎么解决上传限制图片或文件大小问题
May 08 jQuery
vue+iview+less+echarts实战项目总结
Feb 22 Javascript
JavaScript函数、闭包、原型、面向对象学习笔记
Sep 06 Javascript
JavaScript检测浏览器是否支持CSS变量代码实例
Apr 03 Javascript
jQuery源码解读之extend()与工具方法、实例方法详解
Mar 30 #jQuery
jQuery实现Select下拉列表进行状态选择功能
Mar 30 #jQuery
借助node实战JSONP跨域实例
Mar 30 #Javascript
js利用for in循环获取 一个对象的所有属性以及值的实例
Mar 30 #Javascript
Bootstrap实现的经典栅格布局效果实例【附demo源码】
Mar 30 #Javascript
实例详解display:none与visible:hidden的区别
Mar 30 #Javascript
JavaScript+Html5实现按钮复制文字到剪切板功能(手机网页兼容)
Mar 30 #Javascript
You might like
用文本文件制作留言板提示(下)
2006/10/09 PHP
推荐php模板技术[转]
2007/01/04 PHP
二招解决php乱码问题
2012/03/25 PHP
如何用PHP来实现一个动态Web服务器
2015/07/29 PHP
PHP实现活动人选抽奖功能
2017/04/19 PHP
PHP观察者模式示例【Laravel框架中有用到】
2018/06/15 PHP
PHP基础之输出缓冲区基本概念、原理分析
2019/06/19 PHP
浅谈PHP中的那些魔术常量
2020/12/02 PHP
js 调整select 位置的函数
2008/02/21 Javascript
jQuery 常见操作实现方式和常用函数方法总结
2011/05/06 Javascript
判断ie的两种简单方法
2013/08/12 Javascript
jQuery中操控hidden、disable等无值属性的方法
2014/01/06 Javascript
jquery处理json数据实例分析
2014/06/03 Javascript
深入分析原生JavaScript事件
2014/12/29 Javascript
关于延迟加载JavaScript
2015/05/05 Javascript
JavaScript实现添加、查找、删除元素
2015/07/02 Javascript
JS实现的验证身份证及获取地区功能示例
2017/01/16 Javascript
NodeJS实现图片上传代码(Express)
2017/06/30 NodeJs
webstorm和.vue中es6语法报错的解决方法
2018/05/08 Javascript
vue axios请求频繁时取消上一次请求的方法
2018/11/10 Javascript
vue项目首屏加载时间优化实战
2019/04/23 Javascript
layer.open弹层查看缩略图的原图,自适应大小的实例
2019/09/05 Javascript
jquery 插件重新绑定的处理方法分析
2019/11/23 jQuery
python3模拟百度登录并实现百度贴吧签到示例分享(百度贴吧自动签到)
2014/02/24 Python
python创建线程示例
2014/05/06 Python
Python3基础之条件与循环控制实例解析
2014/08/13 Python
Python简单实现自动删除目录下空文件夹的方法
2017/08/29 Python
tensorflow 1.0用CNN进行图像分类
2018/04/15 Python
python实现对输入的密文加密
2019/03/20 Python
Pycharm如何运行.py文件的方法步骤
2020/03/03 Python
Python在字符串中处理html和xml的方法
2020/07/31 Python
我们是伦敦女孩:WalG
2018/01/08 全球购物
汽车驾驶求职信
2013/10/25 职场文书
超市总经理岗位职责
2014/02/02 职场文书
2015元旦家电促销活动策划方案
2014/12/09 职场文书
JavaScript实现简单拖拽效果
2021/09/15 Javascript