programing tip

AngularJS 지시문 동적 템플릿

itbloger 2020. 11. 23. 07:53
반응형

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:'='
        }
    };
});

1) HTML의 속성으로 콘텐츠를 전달하고 있습니다. 이 시도:

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

대신에:

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

2) 지시문의 데이터 부분이 컴파일되고 있으므로 다른 것을 사용해야합니다. 데이터 유형 대신에, 예를 들어 datan 유형.

여기 링크가 있습니다:

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


template디렉티브 정의 객체 속성을 동적 템플릿을 반환하는 함수로 설정할 수 있습니다 .

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

이 시점에서는 범위에 대한 액세스 권한이 없지만을 통해 속성에 액세스 할 수 있습니다 tAttrs.

Now your template is being determined before the compile phase, and you don't need to manually compile it.


You can also do it very straightforward like this:

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

If you need to load your template based on $scope variables you can do it using 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';
        }
      }
    }
  };
});

Reference: https://coderwall.com/p/onjxng/angular-directives-using-a-dynamic-template

참고URL : https://stackoverflow.com/questions/23065165/angularjs-directive-dynamic-templates

반응형