2015-11-03 15 views
0

在創建自定義指令時,如果您想將視圖/模板html放入單獨的文件中,Angular似乎從公用URL加載模板,併爲其創建HTTP請求。你如何要求角模板html?

如何將此模板HTML inline保留在單獨的文件中?

+0

你可以給這個術語的例子: - '你怎麼包含這個模板HTML內聯,而保持在一個單獨的文件?' –

回答

0

使用指令來解決這個

HTML

<div custom-include url="{{url}}"></div> 

指令

app.directive('customInclude', ['$http', '$compile', '$timeout', customInclude]); 
    function customInclude($http, $compile, $timeout) { 
     return { 
      restrict: 'A', 
      link: function link($scope, elem, attrs) { 
       //if url is not empty 
       if (attrs.url) { 
        $http({ method: 'GET', url: attrs.url, cache: true }).then(function (result) { 
         elem.append($compile(angular.element(result.data))($scope)); 
         //after sometime we add width and height of modal 
         $timeout(function() { 
          //write your own code 
         }, 1, false); 
        }); 
       } 
      } 
     }; 
    } 
0

「內聯」,在一個單獨的文件是自打嘴巴。

由於angular是客戶端代碼,因此加載存儲在自己單獨文件中的模板將始終需要http請求。

避免這些請求的唯一方法是將它們與您的其他代碼一起內聯添加,因此不在單獨的文件中。

2

隨着ES6沒有什麼是不可能的:

import yourTemplate from 'path/to/file'; 

// inject $templateProvider in start point of your application 

$templateProvider.put('path/to/file', yourTemplate); 

$templateProvider在自己的簡單$cacheFactory例如,在那裏你可以把任何HTML,任何按鍵,即可以用在NG-包括或簡單地使用你的指令,如下所示:

//Directive 
import yourTemplate from 'path/to/file'; 

被指令配置中使用:

..., 
controller: xxx, 
template: yourTemplate, 
link:() => { ... } 
...