简体   繁体   中英

How to get ng-template content from a single html file?

HTML file - directive 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>

Angular JS code

I am loading this into html file called directive template and then want to get only the ng-template content of editdetails.html how to do that?

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());

Obviously you could read more about $templateCache and script documentation at Official AngularJS website. Other option is to try this one.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM