sourcecode

AngularJS 지시 다이내믹 템플릿

copyscript 2023. 3. 5. 10:16
반응형

AngularJS 지시 다이내믹 템플릿

스코프 값에 따라 다른 템플릿으로 디렉티브를 작성하려고 합니다.

지금까지 한 일이지만 왜 안 되는지 모르겠다.http://jsbin.com/mibeyotu/1/edit

HTML 요소:

<data-type content-attr="test1"></data-type>

지시:

var app = angular.module('myApp', []);

app.directive('dataType', function ($compile) {

    var testTemplate1 = '<h1>Test1</h1>';
    var testTemplate2 = '<h1>Test2</h1>';
    var testTemplate3 = '<h1>Test3</h1>';

    var getTemplate = function(contentType){

        var template = '';

        switch(contentType){
            case 'test1':
                template = testTemplate1;
                break;
            case 'test2':
                template = testTemplate2;
                break;
            case 'test3':
                template = testTemplate3;
                break;
        }

        return template;
    }; 

    var linker = function(scope, element, attrs){
        element.html(getTemplate(scope.content)).show();
        $compile(element.contents())(scope);
    };

    return {
        restrict: "E",
        replace: true,
        link: linker,
        scope: {
            content:'='
        }
    };
});

를 설정할 수 있습니다.template동적 템플릿을 반환하는 함수에 대한 지시 정의 개체의 속성:

restrict: "E",
replace: true,
template: function(tElement, tAttrs) {
    return getTemplate(tAttrs.content);
}

현시점에서는 스코프에 액세스 할 수 없습니다만, 다음의 방법으로 속성에 액세스 할 수 있습니다.tAttrs.

이제 템플릿은 컴파일 단계 전에 결정되므로 수동으로 컴파일할 필요가 없습니다.

다음과 같이 간단하게 할 수도 있습니다.

appDirectives.directive('contextualMenu', function($state) {
    return {
      restrict: 'E',
      replace: true,
      templateUrl: function(){
        var tpl = $state.current.name;
        return '/app/templates/contextual-menu/'+tpl+'.html';
      }
    };
});

1) 콘텐츠를 html 속성으로 전달합니다.이것을 시험해 보세요.

element.html(getTemplate(attrs.content)).show();

다음 대신:

element.html(getTemplate(scope.content)).show();

2) 디렉티브의 데이터 부분은 컴파일 중이므로 다른 것을 사용해야 합니다.데이터 유형(예: datan-type)이 아닌

다음은 링크입니다.

http://jsbin.com/mibeyotu/6/edit

다음을 기준으로 템플릿을 로드해야 하는 경우$scope사용할 수 있는 변수ng-include:

.directive('profile', function() {
  return {
    template: '<ng-include src="getTemplateUrl()"/>',
    scope: {
      user: '=data'
    },
    restrict: 'E',
    controller: function($scope) {
      //function used on the ng-include to resolve the template
      $scope.getTemplateUrl = function() {
        //basic handling
        if ($scope.user.type == 'twitter') {
          return 'twitter.tpl.html';
        }
        if ($scope.user.type == 'facebook') {
          return 'facebook.tpl.html';
        }
      }
    }
  };
});

참고 자료: https://coderwall.com/p/onjxng/angular-directives-using-a-dynamic-template

언급URL : https://stackoverflow.com/questions/23065165/angularjs-directive-dynamic-templates

반응형