angular 可以自定义一些指令,来简化我们前端的工作量。

第一种:简单指令示例

<h3>自定义指令</h3>
<sheng></sheng> <!-- 第一种展示方式 -->

JS示例:

var myApp = angular.module('myApp',[]);
myApp.directive("sheng",function(){
return {
template:"<h1>你好</h1>"
};
});

第二种:引入外部文件

<h3>模板 - 引入外部文件</h3>
<div shi=""></div> <!-- 第二种展示方式 -->

JS示例:

myApp.directive("shi",function(){
return {
templateUrl:"page/template.html" // 使用这种必须要在服务器上测试
};
});

第三种:使用script标签模板

<h3>模板 - script标签</h3>
<qu></qu>
<script id="qu" type="text/ng-template">script标签模板</script>

JS示例:

myApp.directive("qu",function(){
return {
templateUrl:"qu"
};
});

自定义指令的不同实现方式:

当以类名形式编写时,还必须在定义指令时添加restrict属性 (使用属性和标签的方式时不写也可正常显示)

restrict是“限制”的意思,属性值可以为E(element),A(attribute),C(class),当你希望实现方式只能是标签时,可以写restrict:“E”,restrict:“EAC”表示三种方式都可以,以此类推。

五、自定义模板内容

上面的模板内容都是固定的,实际开发中模板的内容都是由项目需要而生成的,如何让每一个模板的内容不一样呢? 使用 transclude

1. 在模板中的标签里添加 ng-transclude,(如果你需要某个标签里的内容自定义就添加ng-transclude属性,如果希望是固定的值就不需要加)

2. 添加属性 transclude:true

3. 在实现自定义指令时,把自定义的内容写在指令标签的里面即可。

下面是在做测试的时候,一个简单的示例:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="./js/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myAppController"> <h3>自定义指令</h3>
<sheng></sheng> <!-- 第一种展示方式 --> <h3>模板 - 引入外部文件</h3>
<div shi=""></div> <!-- 第二种展示方式 --> <h3>模板 - script标签</h3>
<qu></qu>
<script id="qu" type="text/ng-template">script标签模板</script>
</body>
<script type="text/javascript">
var myApp = angular.module('myApp',[]);
myApp.directive("sheng",function(){
return {
template:"<h1>你好</h1>"
};
});
myApp.directive("shi",function(){
return {
templateUrl:"page/template.html" // 使用这种必须要在服务器上测试
};
});
myApp.directive("qu",function(){
return {
templateUrl:"qu"
};
});
myApp.controller('myAppController',['$scope',function($scope){ }]);
</script>
</html>

最新文章

  1. 如何选择合适的CRM客户关系管理软件?
  2. 哈希(Hash)与加密(Encrypt)相关内容
  3. Spring AOP(注解方式)
  4. with check option
  5. HNOI2008越狱(快速幂)
  6. 【制作镜像】virsh
  7. 小A的柱状图
  8. [LeetCode] K-th Symbol in Grammar 语法中的第K个符号
  9. 记一次InputStream引起的乱码
  10. Linux命令速查手册
  11. 取消svn关联文件夹
  12. 【入门详解】MyBatis入门基础详解
  13. PHP实战 新闻管理系统 使用到了bootstrap框架
  14. html5 file 自定义文件过滤
  15. bootstrap.min.css.map HTTP/1.1&quot; 404 1699
  16. sql 备忘
  17. CodeForces 297C Splitting the Uniqueness (脑补构造题)
  18. js_在原有的日期上添加天数输出添加后的日期
  19. 【树形dp】The more, The Better
  20. JBoss jar包冲突及jar加载顺序

热门文章

  1. chrome浏览器插件推荐——Vimium 篇
  2. QLayout布局时自动占满全部的空间。
  3. linux上nginx上配置虚拟主机的相关配置
  4. PHP实现MySQL数据导出为EXCEL(CSV格式)
  5. chrome调试技巧--持续更新
  6. android SDK manager 快速更新【转】
  7. web开发中的安全问题
  8. [转]ASP.NET MVC 5 - 创建连接字符串(Connection String)并使用SQL Server LocalDB
  9. JQuery--使用autocomplete控件进行自己主动输入完毕(相当于模糊查询)
  10. PHP-007(转)