programing

.js 파일에 상대적인 Angular Directive templateUrl

lastmemo 2023. 2. 20. 23:52
반응형

.js 파일에 상대적인 Angular Directive templateUrl

보장할 수는 에게 강제있습니다.directive.js ★★★★★★★★★★★★★★★★★」directive.html(실제 파일명이 아님)을 같은 폴더에 저장합니다.

가 「」를 하는 .directive.js 「 」, 「 」를합니다.templateUrl자기 자신과 상대적인 관계입니다.★★★★★★★★★★★를 설정할 수 있습니까?templateUrldirective.js 파일? 파일?

또는 명령어 자체에 템플릿을 포함시키는 것이 좋습니다.

다른 보다는 상대 할 수 이 좋습니다.directive.js

현재 실행 중인 스크립트파일은 항상 스크립트 배열의 마지막 파일이 되므로 경로를 쉽게 찾을 수 있습니다.

// directive.js

var scripts = document.getElementsByTagName("script")
var currentScriptPath = scripts[scripts.length-1].src;

angular.module('app', [])
    .directive('test', function () {
        return {
            templateUrl: currentScriptPath.replace('directive.js', 'directive.html')
        };
    });

스크립트 이름이 불분명한 경우(예를 들어 여러 스크립트를 하나의 스크립트로 패키지하는 경우) 다음과 같이 하십시오.

return {
    templateUrl: currentScriptPath.substring(0, currentScriptPath.lastIndexOf('/') + 1) 
        + 'directive.html'
};

주의: 폐쇄를 사용하는 경우, 다음과 같이 현재 스크립트가 올바른 시간에 평가되도록 코드를 외부에 두어야 합니다.

// directive.js

(function(currentScriptPath){
    angular.module('app', [])
        .directive('test', function () {
            return {
                templateUrl: currentScriptPath.replace('directive.js', 'directive.html')
        };
    });
})(
    (function () {
        var scripts = document.getElementsByTagName("script");
        var currentScriptPath = scripts[scripts.length - 1].src;
        return currentScriptPath;
    })()
);

디렉티브에 다른 시간에 다른 템플릿을 제공하고 싶다고 말씀하셨듯이 템플릿 자체를 속성으로 디렉티브에 전달하는 것은 어떻습니까?

<div my-directive my-template="template"></div>

'아까부터' 같은 하세요.$compile(template)(scope)지시문 안에 있습니다.

Alon Gubkin의 답변 외에 스크립트의 경로를 저장하고 디렉티브에 삽입하기 위해 즉시 호출된 함수식을 사용하여 상수를 정의할 것을 권장합니다.

angular.module('app', [])

.constant('SCRIPT_URL', (function () {
    var scripts = document.getElementsByTagName("script");
    var scriptPath = scripts[scripts.length - 1].src;
    return scriptPath.substring(0, scriptPath.lastIndexOf('/') + 1)
})())

.directive('test', function(SCRIPT_URL) {
    return {
        restrict :    'A',
        templateUrl : SCRIPT_URL + 'directive.html'
    }
});

이 코드는 routes라는 파일에 있습니다.js

다음 항목이 작동하지 않았습니다.

var scripts = document.getElementsByTagName("script")
var currentScriptPath = scripts[scripts.length-1].src;
var baseUrl = currentScriptPath.substring(0, currentScriptPath.lastIndexOf('/') + 1);

다음과 같이 처리했습니다.

var bu2 = document.querySelector("script[src$='routes.js']");
currentScriptPath = bu2.src;
baseUrl = currentScriptPath.substring(0, currentScriptPath.lastIndexOf('/') + 1);

이 테스트는 다음 블로그를 기반으로 하고 있습니다.요구에 의한 load angular 사용에 관한 것입니다.http://ify.io/lazy-loading-in-angularjs/

require.js는 requireConfig 부트스트랩을 가져옵니다.

requireConfig가 각진 app.js를 생성합니다.

angular app.displays는 내 루트를 낳는다.

나는 같은 코드를 revel web 프레임워크와 asp.net mvc에 의해 제공받았다.revel document.getElementsByTagName("script")에서 my routes.js가 아닌 my require bootstrap js 파일에 대한 경로가 생성되었습니다.ASP에 있습니다.NET MVC는 디버깅 세션 중에 Visual Studio에 주입된 Browser Link 스크립트 요소에 대한 경로를 생성했습니다.

이것은 나의 작업 경로입니다.코드는 다음과 같습니다.

define([], function()
{
    var scripts = document.getElementsByTagName("script");
    var currentScriptPath = scripts[scripts.length-1].src;
    console.log("currentScriptPath:"+currentScriptPath);
    var baseUrl = currentScriptPath.substring(0, currentScriptPath.lastIndexOf('/') + 1);
    console.log("baseUrl:"+baseUrl);
    var bu2 = document.querySelector("script[src$='routes.js']");
    currentScriptPath = bu2.src;
    console.log("bu2:"+bu2);
    console.log("src:"+bu2.src);
    baseUrl = currentScriptPath.substring(0, currentScriptPath.lastIndexOf('/') + 1);
    console.log("baseUrl:"+baseUrl);
    return {
        defaultRoutePath: '/',
            routes: {
            '/': {
                templateUrl: baseUrl + 'views/home.html',
                dependencies: [
                    'controllers/HomeViewController',
                    'directives/app-style'
                ]
            },
            '/about/:person': {
                templateUrl: baseUrl + 'views/about.html',
                dependencies: [
                    'controllers/AboutViewController',
                    'directives/app-color'
                ]
            },
            '/contact': {
                templateUrl: baseUrl + 'views/contact.html',
                dependencies: [
                    'controllers/ContactViewController',
                    'directives/app-color',
                    'directives/app-style'
                ]
            }
        }
    };
});

이것은 레벨에서 실행할 때의 콘솔 출력입니다.

currentScriptPath:http://localhost:9000/public/ngApps/1/requireBootstrap.js routes.js:8
baseUrl:http://localhost:9000/public/ngApps/1/ routes.js:10
bu2:[object HTMLScriptElement] routes.js:13
src:http://localhost:9000/public/ngApps/1/routes.js routes.js:14
baseUrl:http://localhost:9000/public/ngApps/1/ 

또 하나의 장점은 필요한 구성을 활용하여 커스텀 구성을 추가한 것입니다.

customConfig: { baseRouteUrl: '/AngularLazyBaseLine/Home/Content' } 

다음으로 루트 내부에서 다음 코드를 사용하여 취득할 수 있습니다.

var requireConfig = requirejs.s.contexts._.config;
console.log('requireConfig.customConfig.baseRouteUrl:' + requireConfig.customConfig.baseRouteUrl); 

baseurl을 미리 정의해야 할 때도 있고 동적으로 생성해야 할 때도 있습니다.상황에 맞는 선택입니다.

약간 '해키'라고 하는 사람도 있겠지만, 방법이 하나밖에 없는 한, 어떤 것이든 해키라고 생각합니다.
저는 이런 일을 할 수 있어서 운이 좋았습니다.

angular.module('ui.bootstrap', [])
  .provider('$appUrl', function(){
    this.route = function(url){
       var stack = new Error('dummy').stack.match(new RegExp(/(http(s)*\:\/\/)[^\:]+/igm));
       var app_path = stack[1];
       app_path = app_path.slice(0, app_path.lastIndexOf('App/') + 'App/'.length);
         return app_path + url;
    }
    this.$get = function(){
        return this.route;
    } 
  });

그리고 앱에 모듈을 포함시킨 후 앱에서 코드를 사용할 때.
앱 구성 기능:

.config(['$routeProvider', '$appUrlProvider', function ($routeProvider, $appUrlProvider) {

    $routeProvider
        .when('/path:folder_path*', {
            controller: 'BrowseFolderCntrl',
            templateUrl: $appUrlProvider.route('views/browse-folder.html')
        });
}]);

앱 컨트롤러(필요한 경우):

var MyCntrl = function ($scope, $appUrl) {
    $scope.templateUrl = $appUrl('views/my-angular-view.html');
};

새로운 javascript 오류를 생성하고 스택 트레이스를 꺼냅니다.다음으로, 모든 URL(발신측 회선/char 번호 제외)을 해석합니다.
그런 다음 어레이의 첫 번째 파일을 꺼냅니다.이 파일은 코드가 실행되고 있는 현재 파일이 됩니다.

이것은 코드를 중앙 집중화하고 나서두 번째 코드를 꺼내는 경우에도 도움이 됩니다.[1]어레이내의 )를 사용하고, 발신측 파일의 위치를 취득합니다.

여러 사용자가 지적했듯이 정적 파일을 작성할 때 관련 경로가 도움이 되지 않으므로 그렇게 하는 것이 좋습니다.

Angular에는 $templateCache라고 하는 기능이 있습니다.이 기능은 템플릿 파일을 어느 정도 캐시합니다.다음에는 템플릿 파일을 필요로 할 때 실제 요청을 하는 대신 캐시된 버전을 제공합니다.일반적인 사용 방법은 다음과 같습니다.

module = angular.module('myModule');
module.run(['$templateCache', function($templateCache) {
$templateCache.put('as/specified/in/templateurl/file.html',
    '<div>blabla</div>');
}]);
})();

이렇게 해서 둘 다 상대 URL 문제를 해결하고 성능을 향상시킵니다.

물론 템플릿 html 파일을 별도로 갖는다는 아이디어(반응과는 대조적으로)는 매우 좋기 때문에 위의 것 자체로는 좋지 않습니다.여기서 빌드 시스템이 등장합니다.이 시스템은 모든 템플릿 html 파일을 읽고 위와 같은 js를 구성할 수 있습니다.

grunt, gulp, webpack용 html2js 모듈이 여러 개 있으며, 이것이 그 배후에 있는 주요 아이디어입니다.저는 개인적으로 꿀꺽을 많이 사용하기 때문에 특히 꿀꺽-ng-html2js를 좋아합니다.

언급URL : https://stackoverflow.com/questions/21103724/angular-directive-templateurl-relative-to-js-file

반응형