index.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <div ng-app="myApp"> <script type="text/ng-template" id="customTags2"> <div> hello{{name}} </div> </script> <div ng-controller="firstController"> <custom-tags></custom-tags> <custom-tags2></custom-tags2> <!--此處會去渲染script標簽的模板--> </div> </div> <script type="text/javascript" src="../../vendor/angular/angularJs.js"></script> <script type="text/javascript" src="app/index.js"></script> <script> </script> </body> </html>
other.html:
<div>我是其他文件 {{name}}</div>
index.js:
var myApp = angular.module('myApp', [],['$compileProvider',function ($compileProvider) { $compileProvider.directive('customTags',function () { return { restrict:"ECAM", templateUrl:'temp/other.html', replace:true //如果此配置為true則替換指令所在的元素 如果為false或者不指定 則把當前指令追加到所在元素的內部 } }) }]) .directive('customTags2',function () { return{ restrict:"ECAM", templateUrl:"customTags2", //對應為type="text/ng-template" 指定script的標簽id replace:true } }) .controller('firstController',['$scope',function ($scope) { $scope.name = "張三"; //賦值 }]);
運行結果: