source

templateUrl을 즉시 변경할 수 있습니까?

itover 2023. 2. 11. 09:12
반응형

templateUrl을 즉시 변경할 수 있습니까?

디렉티브 범위 내의 값을 전달함으로써 templateUrl을 즉시 변경할 수 있습니까?지시에서 전달된 데이터를 기반으로 페이지를 렌더링하는 컨트롤러에 데이터를 전달하고 싶다.

이렇게 생겼을 수도 있어요

<div> 
   <boom data="{{myData}}" />
</div> 

.directive('boom', function {
        return {
            restrict: 'E',
            transclude: true,
            scope: 'isolate',
            locals: { data: 'bind' },
            templateUrl: "myTemplate({{boom}}})" // <- that of course won't work.
        }
    });

가능하지만, 로드되는 템플릿이 일부 범위 데이터에 의존할 경우 지시문을 사용할 수 없습니다.templateUrl더 이상 속성을 사용할 필요가 없습니다.즉, 하위 수준의 API를 사용해야 합니다.$http그리고.$compile.

대략적으로 당신이 해야 할 일은 (링크 기능에서만 가능) 템플릿의 콘텐츠를 검색하는 것입니다.$http(기억해 두세요)$templateCache!)를 클릭하여 템플릿의 콘텐츠를 컴파일합니다.

그것은 많은 일처럼 들릴지 모르지만 실제로는 오히려 간단하다.제가 추천하고 싶은 건ngInclude이 패턴이 사용되는 지시 소스.

이러한 명령의 개요를 다음에 나타냅니다.

app.directive('boom', function($http, $templateCache, $compile, $parse) {
        return {
            restrict: 'E',
            link: function(scope , iElement, iAttrs) {                            
              var boom = $parse(iAttrs.data)(scope);
              $http.get('myTemplate'+boom, {cache: $templateCache}).success(function(tplContent){
                iElement.replaceWith($compile(tplContent)(scope));                
              });              
            } 
        }
    });

그것이 로 사용될 것이라고 가정하고<boom data='name'></boom>. 여기서 작업 : http://plnkr.co/edit/TunwvhPPS6MdiJxpNBg8?p=preview

속성평가가 다음에서 변경되었음을 유의하시기 바랍니다.{{name}}템플릿은 처음에 한 번만 결정되어야 하기 때문에 속성 구문 분석으로 이동합니다.

이것은 Angular 버전 1.1.4+의 신기능입니다.현재 불안정한(1.1.5)을 사용하면 디렉티브의 템플릿 URL에 함수를 전달할 수 있습니다.함수의 두 번째 파라미터는 다음과 같은 Atribute Directive 값입니다.

여기 공식 변경 내용을 보여주는 미공개 문서에 대한 링크가 있습니다.

사용방법partials/template1.html템플릿 URL 로서

HTML:

<div sub_view="template1"></div>

지시:

.directive('subView', [()->
  restrict: 'A'
  # this requires at least angular 1.1.4 (currently unstable)
  templateUrl: (notsurewhatthisis, attr)->
    "partials/#{attr.subView}.html"
])

나도 비슷한 문제가 있었다.

 return {
        restrict: 'AE',
        templateUrl: function(elm,attrs){return (attrs.scrolled='scrolled' ?'parts/scrolledNav.php':'parts/nav.php')},
        replace: true,

partnersSite.directive('navMenu', function () {
    return {
        restrict: 'AE',
        templateUrl: function(elm,attrs){return (attrs.scrolled='scrolled' ?'parts/scrolledNav.php':'parts/nav.php')},
        replace: true,
        link: function (scope, elm, attrs) {
            scope.hidden = true;
            //other logics
        }
    };
});
<nav-menu scrolled="scrolled"></nav-menu>

pkozlowski.opensource에서 답변을 조금 바꿨습니다.

다음부터는

var boom = $parse(iAttrs.data)(scope);

수신인:

var boom = scope.data.myData

그것은 나에게 효과가 있었고, 그것을 사용할 수 있다.

<boom data="{{myData}}" /> 

지시문에 기재되어 있습니다.

이 질문은 다음과 같이 ng-include로 수정됩니다.

MyApp.directive('boom', function() {
    return {
      restrict: 'E',
      transclude: true,
      scope: 'isolate',
      locals: { data: 'bind' },
      templateUrl: '<div ng-include="templateUrl"></div>',
      link: function (scope) {
        function switchTemplate(temp) {
          if (temp == 'x')
          { scope.templateUrl = 'XTemplate.html' }
          else if (temp == 'y')
          { scope.templateUrl = 'YTemplate.html' }
        }
      }
    }
});

디렉티브의 링크함수에 임의의 temp 파라미터를 사용하여 switchTemplate 함수를 호출합니다.

이 답변은 이전 답변과 관련된 몇 가지 문제를 해결하는 후속 답변입니다.특히 템플릿은 한 번만 컴파일됩니다(페이지에 템플릿이 많이 있는 경우 중요하며, 템플릿이 링크된 후 템플릿에 대한 변경을 감시합니다).또한 "replace: true"를 사용할 때 내부적으로 angular가 수행하는 우아한 방식은 아니지만 원래 요소의 클래스 및 스타일을 템플릿으로 복사합니다.template 또는 templateUrl 함수를 사용하는 현재 지원되는 각도 방식과는 달리 스코프 정보를 사용하여 로드할 템플릿을 결정할 수 있습니다.

.directive('boom', ['$http', '$templateCache', '$compile', function ($http, $templateCache, $compile) {
    //create a cache of compiled templates so we only compile templates a single time.
    var cache= {};
    return {
        restrict: 'E',
        scope: {
            Template: '&template'
        },
        link: function (scope, element, attrs) {
            //since we are replacing the element, and we may need to do it again, we need
            //to keep a reference to the element that is currently in the DOM
            var currentElement = element;
            var attach = function (template) {
                if (cache[template]) {
                    //use a cloneAttachFn so that the link function will clone the compiled elment instead of reusing it
                    cache[template](scope, function (e) {
                        //copy class and style
                        e.attr('class', element.attr('class'));
                        e.attr('style', element.attr('style'));
                        //replace the element currently in the DOM
                        currentElement.replaceWith(e);
                        //set e as the element currently in the dom
                        currentElement = e;
                    });
                }
                else {
                    $http.get('/pathtotemplates/' + template + '.html', {
                        cache: $templateCache
                    }).success(function (content) {
                        cache[template] = $compile(content);
                        attach(template);
                    }).error(function (err) {
                        //this is something specific to my implementation that could be customized
                        if (template != 'default') {
                            attach('default');
                        }
                        //do some generic hard coded template
                    });
                }
            };

            scope.$watch("Template()", function (v, o) {
                if (v != o) {
                    attach(v);
                }
            });
            scope.$on('$destroy', function(){
                currentElement.remove();
            });
        }
    };
} ])

을 사용하다 사용법에는 .templateUrl자주 사용하지 않는 제품이죠.URL을 반환하는 함수일 수 있습니다.그 함수에는 몇 가지 인수가 있습니다.더 이상 원하신다면 여기 멋진 기사가 있습니다.

http://www.w3docs.com/snippets/angularjs/dynamically-change-template-url-in-angularjs-directives.html

언급URL : https://stackoverflow.com/questions/14632260/can-you-change-templateurl-on-the-fly

반응형