微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

AngularJS 自定义指令详解及示例代码

自定义指令中使用AngularJS扩展HTML的功能自定义指令使用的“指令”的功能定义。自定义指令只是替换了它被激活的元素。引导过程中AngularJS应用程序找到了匹配的元素,并做好使用自定义指令compile()方法一次活动再处理使用基于指令的范围自定义指令link()方法的元素。 AngularJS提供支持,以下列元素的类型来创建自定义指令。

Element directives - 指令遇到时激活一个匹配的元素。

Attribute - - 指令遇到时激活一个匹配的属性

CSS - - 指令遇到时激活匹配CSS样式。

Comment - - 指令遇到时激活匹配的注释。

了解自定义指令

定义自定义的HTML标签


定义自定义指令来处理上面的自定义HTML标签

<div class="jb51code">
<pre class="brush:js;">
var mainApp = angular.module("mainApp",[]);

//Create a directive,first parameter is the html element to be attached.
//We are attaching student html tag.
//This directive will be activated as soon as any student element is encountered in html
mainApp.directive('student',function() {
//define the directive object
var directive = {};
//restrict = E,signifies that directive is Element directive
directive.restrict = 'E';
//template replaces the complete element with its text.
directive.template = "Student: {{student.name}},Roll No: {{student.rollno}}";
//scope is used to distinguish each student element based on criteria.
directive.scope = {
student : "=name"
}
//compile is called during application initialization. AngularJS calls it once when html page is loaded.
directive.compile = function(element,attributes) {
element.css("border","1px solid #cccccc");
//linkFunction is linked with each element with scope to get the element specific data.
var linkFunction = function($scope,element,attributes) {
element.html("Student: "+$scope.student.name +",Roll No: "+$scope.student.rollno+"
");
element.css("background-color","#ff00ff");
}
return linkFunction;
}
return directive;
});

定义控制器以更新范围为指令。在这里,我们使用name属性值作为子的作用域。

rush:js;"> mainApp.controller('StudentController',function($scope) { $scope.Mahesh = {}; $scope.Mahesh.name = "Mahesh Parashar"; $scope.Mahesh.rollno = 1;

$scope.Piyush = {};
$scope.Piyush.name = "Piyush Parashar";
$scope.Piyush.rollno = 2;
});

例子

rush:js;"> Angular JS Custom Directives

AngularJS Sample Application


结果

在Web浏览器中打开textAngularJS.html。看到结果如下:

以上就是对AngularJS的自定义指令资料整理,后续继续补充,谢谢大家对本站的支持

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


什么是深拷贝与浅拷贝?深拷贝与浅拷贝是js中处理对象或数据复制操作的两种方式。‌在聊深浅拷贝之前咱得了解一下js中的两种数据类型:
前言 今天复习了一些前端算法题,写到一两道比较有意思的题:重建二叉树、反向输出链表每个节点 题目 重建二叉树: 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列 {1,2,4,7,3,5,6,8} 和中序遍历序列 {
最近在看回JavaScript的面试题,this 指向问题是入坑前端必须了解的知识点,现在迎来了ES6+的时代,因为箭头函数的出现,所以感觉有必要对 this 问题梳理一下,所以刚好总结一下JavaScript中this指向的问题。
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小
JS怎么获取当前时间戳
JS如何判断对象是否为数组
JS怎么获取图片当前宽高
JS对象如何转为json格式字符串
JS怎么获取图片原始宽高
怎么在click事件中调用多个js函数
js如何往数组中添加新元素
js如何拆分字符串
JS怎么对数组内元素进行求和
JS如何判断屏幕大小
js怎么解析json数据
js如何实时获取浏览器窗口大小
原生JS实现别踩白块小游戏(五)