angular 可以自定义一些指令,来简化我们前端的工作量。
第一种:简单指令示例:
<h3>自定义指令h3> <sheng>sheng>
JS示例:
var myApp = angular.module('myApp',[]); myApp.directive("sheng",function(){ return { template:"你好
" }; });
第二种:引入外部文件:
<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>Documenttitle>
<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:"你好
"
};
});
myApp.directive("shi",function(){
return {
templateUrl:"page/template.html" // 使用这种必须要在服务器上测试
};
});
myApp.directive("qu",function(){
return {
templateUrl:"qu"
};
});
myApp.controller('myAppController',['$scope',function($scope){
}]);
script>
html>