ngInclude与script加载模板

ng-include:

 官网实例:

    <p>ng-include:</p>
    <select ng-model="template" ng-options="t.name for t in templates">
        <option value="">(blank)</option>
    </select>
    url of the template: <span>{{template.url}}</span>
    <div>
        <div ng-include="template.url"></div>
    </div>
$scope.templates = [
    {'name':'template1.html','url':'ngincludetemplate1.html'},                                     
    {'name':'template2.html','url':'ngincludetemplate2.html'}
];
$scope.template = $scope.templates[0];
ngincludetemplate1.html:
<p>content of ngincludetemplate1</p>
ngincludetemplate2.html:
<p>content of ngincludetemplate2</p>

选择的是template1.html时会显示ngincludetemplate1.html页面的内容:相当于<div ng-include=" 'ngincludetemplate1.html' "></div>

选择的是template2.html时会显示ngincludetemplate2.html页面的内容:相当于<div ng-include=" 'ngincludetemplate2.html' "></div>

也可以简单地写成如下形式:

<div ng-include=" 'ngIncludetemplate2.html' "></div>
<div ng-include="tpl"></div>
<div ng-include src="tpl"></div>
$scope.tpl = 'ngIncludetemplate2.html';

此处的值是字符串,所以直接在ng-include写值时要加上''(单引号),或者在js定义一个变量,ng-include引入值时引用变量名即可。

script:

    <div ng-include="'template1.html'"></div><!--直接引用id值(字符串类型)-->
    <div ng-include src="'template2.html'"></div><!--src:直接引用id值(字符串类型)-->
    <div ng-include="scriptTpl3"></div><!--引用变量,变量值是id值(字符串类型)-->
    <div ng-include src="scriptTpl4"></div><!--src:引用变量,变量值是id值(字符串类型)-->
    <script type="text/ng-template" id="template1.html">
         使用script加载的模板,ng-include字符串
    </script>
    <script type="text/ng-template" id="template2.html">
        使用script加载的模板,ng-include src字符串
    </script>
    <script type="text/ng-template" id="template3.html">
        使用script加载的模板,ng-include变量
    </script>
    <script type="text/ng-template" id="template4.html">
        使用script加载的模板,ng-include src变量
    </script>
$scope.scriptTpl3 = 'template3.html';
$scope.scriptTpl4 = 'template4.html';

这里需要注意,type="text/ng-template"是指明这是ng模板,id属性是指实际使用模板时的一个引用,标签之间的内容才是实际的模板内容。而且,需要注意,id绝对不是URL,这个script标签绝对不会发出HTTP请求。 
实际应用模板时候,使用ID属性,即可从内存中获取对应数据。

参考:https://www.zybuluo.com/bornkiller/note/6023

原文地址:https://www.cnblogs.com/loveamyforever/p/6093774.html