2017-08-11 78 views
0

HTML文件 - 指令模板如何從一個html文件中獲取ng-template內容?

<div class='class1'> 
    <span ng-show="Edit1"> 
     <script type="text/ng-template" id="editdetails.html"> 
      <div class="modal"> 
       <h3>Update Unit Details</h3> 
       <input type='text' name='email' value=''> 
      </div> 
     </script> 
    </span> 
</div> 
<div class='class2'> 
    <span ng-show="Edit2"> 
       Some content 
    </span> 
</div> 

角JS代碼

我加載到這個稱爲HTML文件指令模板,然後想只有ng-template內容的editdetails.html怎麼做?

var directiveTemplate = null; 
var req = new XMLHttpRequest(); 
req.onload = function() { 
      directiveTemplate = this.responseText; 
    }; 
var url1 = 'directivetemplate.html'; 
req.open('get', url1, false); 
req.send(); 
$templateCache.put('template.html', directiveTemplate); 
$edittemplate=directiveTemplate; 
//The below code doesn't get me content inside the editdetails 
$templateCache.put('editdetails.html',$edittemplate.filter('#editdetails.html').html()); 

回答

2

很明顯,你可以閱讀在官方網站AngularJS更多$templateCachescript文檔。其他選擇是嘗試這一個。

angular 
 
    .module("Example", []) 
 
    .controller("ExampleCtrl", ExampleCtrl); 
 
    
 
    ExampleCtrl.$inject = ['$scope', '$templateCache']; 
 
    function ExampleCtrl($scope, $templateCache) { 
 
    $scope.getContent = function() { 
 
     var script = document.getElementsByTagName("script"); 
 
     var id = script[2].id; 
 
     var htmlContent = $templateCache.get(id); 
 
     document.getElementById("display").innerHTML = htmlContent; 
 
    }; 
 
    }
/* Styles go here */ 
 
.content { 
 
    background-color: green; 
 
    color: white; 
 
    padding: 10px; 
 
} 
 

 
.button { 
 
    width: 150px; 
 
    padding: 10px; 
 
    background-color: red; 
 
    color: white; 
 
    border: 0px white solid; 
 
    border-radius: 5px; 
 
}
<!DOCTYPE html> 
 
<html ng-app="Example"> 
 
    <head> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> 
 
    </head> 
 
    <body ng-controller="ExampleCtrl"> 
 
    <script type="text/ng-template" id="templateId.html"> 
 
     <p class="content">This is the content of the template</p> 
 
    </script> 
 
    <p> 
 
     <input type="button" class="button" ng-click="getContent()" value="Get Template's Content"> 
 
    </p> 
 
    <div id="display"></div> 
 
    </body> 
 
</html>