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 相关文章推荐
javascript算法学习(直接插入排序)
Apr 12 Javascript
JQuery获取浏览器窗口内容部分高度的代码
Feb 24 Javascript
js获取html参数及向swf传递参数应用介绍
Feb 18 Javascript
解决css和js的{}与smarty定界符冲突问题的两种方法
Sep 10 Javascript
javascript动态添加、修改、删除对象的属性与方法详解
Jan 27 Javascript
js对图片base64编码字符串进行解码并输出图像示例
Mar 17 Javascript
深入分析escape()、encodeURI()、encodeURIComponent()的区别及示例
Aug 04 Javascript
js实现文章文字大小字号功能完整实例
Nov 01 Javascript
AngularJS入门教程之学习环境搭建
Dec 06 Javascript
AngularJS通过$location获取及改变当前页面的URL
Sep 23 Javascript
Node.js通过身份证号验证年龄、出生日期与性别方法示例
Mar 09 Javascript
layui表格 返回的数据状态异常的解决方法
Sep 10 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
Syphon 虹吸式咖啡壶冲煮–拨动法
2021/03/03 冲泡冲煮
用定制的PHP应用程序来获取Web服务器的状态信息
2006/10/09 PHP
php文件上传、下载和删除示例
2020/08/28 PHP
10个值得深思的PHP面试题
2016/11/14 PHP
完美解决thinkphp唯一索引重复时出错的问题
2017/03/31 PHP
javascript 进阶篇2 CSS XML学习
2012/03/14 Javascript
XMLHttpRequest处理xml格式的返回数据(示例代码)
2013/11/21 Javascript
javascript匿名函数应用示例介绍
2014/03/07 Javascript
jQuery插件slider实现拖动滑块选取价格范围
2015/04/30 Javascript
jquery按回车键实现表单提交的简单实例
2016/05/25 Javascript
对比分析Django的Q查询及AngularJS的Datatables分页插件
2017/02/07 Javascript
JS实现最简单的冒泡排序算法
2017/02/15 Javascript
微信小程序 仿美团分类菜单 swiper分类菜单
2017/04/12 Javascript
详解vue过滤器在v2.0版本用法
2017/06/01 Javascript
用vue封装插件并发布到npm的方法步骤
2017/10/18 Javascript
webpack 静态资源集中输出的方法示例
2018/11/09 Javascript
JavaScript模板引擎原理与用法详解
2018/12/24 Javascript
详解JS实现系统登录页的登录和验证
2019/04/29 Javascript
vue.js实现数据库的JSON数据输出渲染到html页面功能示例
2019/08/03 Javascript
探究python中open函数的使用
2016/03/01 Python
Python的Asyncore异步Socket模块及实现端口转发的例子
2016/06/14 Python
浅谈numpy库的常用基本操作方法
2018/01/09 Python
python删除服务器文件代码示例
2018/02/09 Python
Window环境下Scrapy开发环境搭建
2018/11/18 Python
django orm 通过related_name反向查询的方法
2018/12/15 Python
python导入pandas具体步骤方法
2019/06/23 Python
python字符串分割及字符串的一些常规方法
2019/07/24 Python
django 微信网页授权登陆的实现
2019/07/30 Python
Python 中的 import 机制之实现远程导入模块
2019/10/29 Python
Python 实现递归法解决迷宫问题的示例代码
2020/01/12 Python
python中if及if-else如何使用
2020/06/02 Python
css3实现可滑动跳转的分页插件示例
2014/05/08 HTML / CSS
中专生的个人自我评价
2013/12/11 职场文书
元旦文艺汇演主持词
2014/03/26 职场文书
交通事故和解协议书
2014/09/25 职场文书
《圆的周长》教学反思
2016/02/17 职场文书