简体   繁体   English

动态包含角度指令

[英]Dynamically include directive in angular

I have a situation where I would like to dynamically include directives/components to an angular template. 我有一种情况,我想动态地将指令/组件包含在角度模板中。 The reason to why I want this is that I'm writing a dashboard which should be easy to extend with new widgets. 之所以要这样做,是因为我正在编写一个仪表板,该仪表板应该易于通过新的小部件进行扩展。 I really like the directive/component thinking in angular and would prefer to be able to make a directive of each widget. 我真的很喜欢角度的指令/组件思考,并且希望能够为每个小部件制定指令。 I would then like to add each widget with an ng-repeat or something similar. 然后,我想为每个小部件添加ng-repeat或类似名称。 This would make it very easy to add new widgets over time. 随着时间的推移,这将使添加新的小部件变得非常容易。 My questions are first of all if this thinking is sound and secondly if anyone know if someone has written something like this that I can start with. 我的问题首先是,如果这种想法是正确的,其次,如果有人知道是否有人写过这样的文章,我可以从这里开始。

Example

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

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

Something like this worked for me: 这样的事情对我有用:

Your view: 您的看法:

    <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>

Your controller: 您的控制器:

        $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'
                }]
            ]     
        };

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

use ng-if it creats elements on demand 使用ng-(如果需要)创建元素

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

Controller 控制者

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM