失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > angularJS 自定义指令 属性:templateUrl

angularJS 自定义指令 属性:templateUrl

时间:2018-11-21 08:27:19

相关推荐

angularJS 自定义指令 属性:templateUrl

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结果:

如果觉得《angularJS 自定义指令 属性:templateUrl》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。