您的位置:首页 > Web前端 > AngularJS

angularJS 自定义指令 属性:templateUrl

2016-10-21 12:06 429 查看
    angularJS自定义指令中,设置指令的属性template可以定义需要的dom元素,除了使用template,还可以用templateUrl,这个templateUrl可以设置为一个页面的相对路径,如:templateUrl : ' tmp/other.html ' ,意为使用other.html的内容作为模板dom。  或者把templateUrl设置为一个id,如:templateUrl : ' customDiv2 ' ,意为使用customDiv2的内容作为模板dom,但要注意customDiv2标签是这样的:

<script type="text/ng-template" id="customDiv2">
<div>
hello {{name}} customDiv2内容
</div>
</script>
示例:
文件结构:
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../../vendor/angular/angularjs.js"></script>
<script src="app/index.js"></script>
</head>
<body>
<div ng-app="myApp">

<div ng-controller="firstController">
<h3>custom-tags指令:</h3>
<custom-tags></custom-tags>
<br>
<h3>custom-tags2指令:</h3>
<custom-tags2></custom-tags2>
</div>

<!--custom-tags2指令的dom模板-->
<script type="text/ng-template" id="customDiv2">
<div>
模板customDiv2的内容 {{name}}
</div>
</script>

</div>
</body>
</html>
other.html:
<div>
other页面的内容 {{name}}
</div>
index.js:
angular.module('myApp',[])
.directive('customTags',function(){
return {
restrict:'ECAM',
templateUrl:'tmp/other.html', //用法1,以另一个页面为模板,注意相对路径是针对index.html的
replace:true
}
})
.directive('customTags2',function(){
return {
restrict:'ECAM',
templateUrl:'customDiv2', //用法2:以id="customDiv2"的元素为模板
replace:true
}
})
.controller('firstController',['$scope',function($scope){
$scope.name='张三';
}]);
运行index.html结果:

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: