2

这是我的代码的一小部分:

<div class="list-group">
    <div class="list-group-item list-group-item-default text-center">{{p.Name}}</div>
    <div class="list-group-item">
        <!--Using bootstrap form-group for each field -->
        <div ng-repeat="f in p.Fields">

            <!--Here I want to inject components dynamically-->
            <!--<text-field></text-field>-->

        </div>
    </div>
</div>

在 我需要根据条件动态<div ng-repeat="f in p.Fields">...</div>注入相应的组件,例如<text-field><text-area-field>...

if (f.type == "TEXTFIELD") >>> 注入<text-field>组件
if (f.type == "TEXTAREAFIELD") >>> 注入<text-area-field>组件

等等...

最好的方法是什么?谢谢。

4

2 回答 2

2

你可以这样做:

<div class="list-group">
    <div class="list-group-item list-group-item-default text-center">{{p.Name}}</div>
    <div class="list-group-item">
        <!--Using bootstrap form-group for each field -->
        <div ng-repeat="f in p.Fields">

            <div ng-if="f.type == 'TEXTFIELD'">
               <text-field></text-field>
            </div>

            <div ng-if="f.type == 'TEXTAREAFIELD'">
               <text-area-field></text-area-field>
            </div>

        </div>
    </div>
</div>
于 2016-08-15T13:18:50.177 回答
2

这取决于您打印到页面的输入是否也需要由 Angular 使用(ng-model)。

如果是这样,您需要$compile提供程序。

我建议制定一个指令来处理这个问题。你可以有 :

 <div ng-repeat="f in p.Fields">
      <x-your-directive params={{f}}>
 </div>

在您的指令中,您将收到要解析的数据attrs.params

You then need to inject yourself the $compile, the same way as you would for $scope, services, etc.

You could then apply the new input with angular.element (which is jQLite).

To do so, and for angular to understand the newly created DOM element, that's where you use $compile.

$compile will tell angular to re-parse the element dynamically.

Example:

angular.module('your_module', []).directive('yourDirective', ['$scope', '$compile', function($scope, $compile) {
    return {
        restrict: 'E',
        controllerAs: 'YourCtrl',
        controller: [function() {}],
        link: function ($scope, element, attrs, ctrl) {
            // Switch case on attrs.params (which is f in p.Fields)
            if (attrs.params === 'TEXTFIELD') {
                element.html($compile('<input type="text"/>')($scope))
            }
        }
    }
}])

The cool thing about this, is that it works for directives also (the printing part). Therefor, if you want to dynamically add Directives to your DOM, you can :)

于 2016-08-15T13:37:21.227 回答