首页 > 代码库 > Directive
Directive
1. 指令(Directive):实现语义化的标签
<!DOCTYPE html>
<html ng-app="helloApp">
<head>
<meta charset=utf-8>
<title>hello directive</title>
</head>
<body>
<hello>abc</hello>
<script type="text/javascript" src="../angularjs-1.2.2/angular.js"></script>
<script type="text/javascript" src="helloDirective.js"></script>
</body>
</html>
<html ng-app="helloApp">
<head>
<meta charset=utf-8>
<title>hello directive</title>
</head>
<body>
<hello>abc</hello>
<script type="text/javascript" src="../angularjs-1.2.2/angular.js"></script>
<script type="text/javascript" src="helloDirective.js"></script>
</body>
</html>
//helloDirective.js
var helloModule = angular.module("helloApp", []);
helloModule.directive("hello", function() {
return {
restrict: ‘E‘ ,
template: "<div>Hi City</div>",
replace: true
};
});
var helloModule = angular.module("helloApp", []);
helloModule.directive("hello", function() {
return {
restrict: ‘E‘ ,
template: "<div>Hi City</div>",
replace: true
};
});
实现效果如下:
JS代码中:restrict: ‘E‘,表示声明指令为元素。指令声明的方式有:‘E‘(元素)、‘A‘(属性)、‘C‘(样式类)、‘M‘(注释)。 template: "<div>Hi City</div>",表示指令对应的模板内容。replace: true,表示<hello>会被模板内容替换
2. ng-transclude属性
<!DOCTYPE html>
<html ng-app="helloApp">
<head>
<meta charset=utf-8>
<title>transclude</title>
</head>
<body>
<hello>
<br/>
<span>子内容1</span>
<br/>
<span>子内容2</span>
</hello>
<hello></hello>
<script type="text/javascript" src="../angularjs-1.2.2/angular.js"></script>
<script type="text/javascript" src="transclude.js"></script>
</body>
</html>
<html ng-app="helloApp">
<head>
<meta charset=utf-8>
<title>transclude</title>
</head>
<body>
<hello>
<br/>
<span>子内容1</span>
<br/>
<span>子内容2</span>
</hello>
<hello></hello>
<script type="text/javascript" src="../angularjs-1.2.2/angular.js"></script>
<script type="text/javascript" src="transclude.js"></script>
</body>
</html>
//transclude.js
var helloModule = angular.module("helloApp", []);
helloModule.directive("hello", function() {
return {
restrict: ‘E‘,
template: "<div>Hi City<div ng-transclude></div></div>",
transclude: true
};
});
var helloModule = angular.module("helloApp", []);
helloModule.directive("hello", function() {
return {
restrict: ‘E‘,
template: "<div>Hi City<div ng-transclude></div></div>",
transclude: true
};
});
效果如下所示:
从上述效果中,发现原来hello标签中的子内容还被保留着,放在了ng-transclude标识的模板标签span中。并且transclude.js文件中需要给hello指令添加transclude:true属性。
3. compile和link
compile阶段进行标签解析和变换,link阶段进行数据绑定操作。
Directive
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。