programing

파일에서 AngularJs 변수로 HTML 템플릿 로드

golfzon 2023. 3. 20. 23:48
반응형

파일에서 AngularJs 변수로 HTML 템플릿 로드

HTML을 리치 텍스트 편집기에 바인딩해야 하는 양식을 사용하고 있습니다.이 HTML 콘텐츠를 저장하는 가장 좋은 방법은 HTML 파일입니다.

HTML 템플릿을 파일에서 로드하여 변수에 할당하는 방법을 잘 모르겠습니다.

디렉티브는 templateUrl을 사용할 때 이를 수행할 수 있는 것으로 보입니다.컨트롤러 내부에 동일한 것을 달성하기 위해 각도로 낮은 수준의 api가 있는지 궁금합니다.

를 사용하면 HTML 페이지에 템플릿을 삽입하지 않고도 URL별로 템플릿을 로드할 수 있습니다.템플릿이 이미 로드된 경우 캐시에서 가져옵니다.

app.controller('testCtrl', function($scope, $templateRequest, $sce, $compile){
    // Make sure that no bad URLs are fetched. You can omit this if your template URL is
    // not dynamic.
    var templateUrl = $sce.getTrustedResourceUrl('nameOfTemplate.html');

    $templateRequest(templateUrl).then(function(template) {
        // template is the HTML template as a string

        // Let's put it into an HTML element and parse any directives and expressions
        // in the code. (Note: This is just an example, modifying the DOM from within
        // a controller is considered bad style.)
        $compile($("#my-element").html(template).contents())($scope);
    }, function() {
        // An error has occurred
    });
});

이 방법은 수동적인 방법이라는 점에 유의하십시오.대부분의 경우 템플릿을 가져오는 디렉티브를 정의하는 이 바람직합니다.templateUrl소유물.

모든 템플릿이 캐시에 로드됩니다.템플릿에 액세스하기 위해 사용할 수 있는 $templateCache 서비스가 있습니다.

app.controller('testCtrl', function($scope, $templateCache){
    var template = $templateCache.get('nameOfTemplate.html');
});

언급URL : https://stackoverflow.com/questions/24496201/load-html-template-from-file-into-a-variable-in-angularjs

반응형