Render a directive inside another directive (within repeater template)

前端 未结 2 2027
没有蜡笔的小新
没有蜡笔的小新 2021-02-09 08:01

I am trying to render a directive inside another directive (not sure if the repeater inside the template is working this), and it seems to just output as text rather than compil

相关标签:
2条回答
  • 2021-02-09 08:42

    I managed to work around this issue by re-writing the code:

    First I updated the template code as follows:

    template: '<div class="views">' +
              '    <div class="view-wrapper" ng-repeat="view in views">' +
              '        <div view="{{view.dir}}"></div>' +
              '    </div>' +
              '</div>',
    

    Note that I created a new 'view' directive. Next the view directive definition as follows:

    app.directive('view', ['$compile', function (compile) {
    
        return {
            restrict: 'A',
            scope: {
                view: '@'
            },
            replace: true,   
            template: '<div class="view"></div>',
    
            controller: ['$scope', function (scope) {
                scope.$watch('view', function (value) {
                    scope.buildView(value);
                });
            }],
    
            link: function (scope, elm, attrs) {
    
                scope.buildView = function (viewName) {
                    var view = compile('<div ' + viewName + '></div>')(scope);
                    elm.append(view);
                }
            }
        }
    }]);
    

    So essentially, the view.dir variable is passed as an attribute to the 'view' directive, which then watches it's value and compiles a template with the directive in it.

    0 讨论(0)
  • 2021-02-09 08:47

    This is in part a timing problem...I think that by the time it's resolving the {{}} expressions, it's already parsed out and rendered directives. It's not the nesting or the repeater that are the problem, per se.

    What you're after here, though, is 'decide which directive to render based on the value of a variable'. There are a couple ways to do that.

    Here's one that should work, though it might not scale as nicely as you'd like:

    <div class='views' ng-repeat='view in views'>
      <div ng-switch='view.dir'>
        <div ng-when='my-dir-one' my-dir-one />
        <div ng-when='my-dir-two' my-dir-two />
        <div ng-when='my-dire-three' my-dir-three />
      </div>
    </div>
    

    Other options for similar tricks: it looks like you could use ngBindTemplate to take a string from your data and use it as the template for an element. This would probably permit some tricky (and illegible) behavior.

    You can specify a directive for an element as a class, but I don't know whether using ngClass to do this would allow you to dynamically select the directive, or whether that would come too late in the pipeline.

    0 讨论(0)
提交回复
热议问题