动态地包含角度指令

时间:2015-06-15 09:49:00

标签: javascript angularjs

我有一种情况,我想动态地将指令/组件包含到角度模板中。我想要这个的原因是我正在编写一个仪表板,它应该很容易用新的小部件扩展。我非常喜欢使用angular的指令/组件思考,并且希望能够对每个小部件进行指令。然后我想用ng-repeat或类似的东西添加每个小部件。这样可以很容易地随着时间的推移添加新的小部件。我的问题首先是如果这个想法是合理的,其次如果有人知道是否有人写过我可以开始的这样的东西。

实施例

vm.widgets = [{
    component: 'widgetA'
},{
    component: 'widgetB'
}]

<div ng-repeat="widget in dashboard.widgets">
    <ng-include-component name="widget.component">
</div>

3 个答案:

答案 0 :(得分:1)

这样的事情对我有用:

您的观点:

    <div ng-repeat="row in components">
        <div class="row">
            <div ng-repeat="col in row">
                <div class="col-md-{{col.width}}" ng-include="col.url"/>
            </div>
        </div>
    </div>

你的控制器:

        $scope.components = {
            'Row1': [
                [{
                    url: '/views/widget1.html',
                    width: '4'
                }, {
                    url: '/views/widget2.html',
                    width: '8'
                }]
            ],
            'Row2': [
                [{
                    url: '/views/widget3.html',
                    width: '4'
                }, {
                    url: '/views/widget4.html',
                    width: '4'
                }, {
                    url: 'views/widget5.html',
                    width: '4'
                }]
            ]     
        };

答案 1 :(得分:0)

我创建了自己的指令,完成了我在用例https://gist.github.com/Abrissirba/157e4c3bb87e724b35e1中所要求的内容。

答案 2 :(得分:-1)

使用ng-if它按需创建元素

<div ng-if="flag">
<div ng-repeat="widget in dashboard.widgets">
    <custom-directive name="{{widget.component}}">
</div>
</div>

控制器

app.directive('customDirective',fucntion(){
  return {
        restrict: 'A',
        scope:false,
        link: function (scope, elem, attr, ctrl) {
    scope.widgets = [{
        component: 'widgetA'
    },{
        component: 'widgetB'
    }];
  }
});
相关问题