AngularJS directive dynamic templates

前端 未结 4 1583
悲&欢浪女
悲&欢浪女 2020-12-04 08:06

I\'m trying to make directive with differtent templates based on scope value.

This is what i done so far which i don\'t know why doesn\'t work http://jsbin.com/mibey

相关标签:
4条回答
  • 2020-12-04 08:43

    You can set the template property of your directive definition object to a function that will return your dynamic template:

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

    Notice that you don't have access to scope at this point, but you can access the attributes through tAttrs.

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

    0 讨论(0)
  • 2020-12-04 08:51

    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

    0 讨论(0)
  • 2020-12-04 08:54

    1) You are passing content as attribute in your html. Try this:

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

    instead of:

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

    2) data part of directive is getting compiled so you should use something else. Instead of data-type, e.g. datan-type.

    Here is the link:

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

    0 讨论(0)
  • 2020-12-04 08:54

    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';
          }
        };
    });
    
    0 讨论(0)
提交回复
热议问题