【问题标题】:AngularJS dynamically injecting controller, class etcAngularJS 动态注入控制器、类等
【发布时间】:2015-04-28 16:10:18
【问题描述】:

我有一个动态构建的小部件列表。 每个小部件由 html、类、控制器和名称表示。其中一些可能是空的(例如,并非所有小部件都需要控制器)。 然后我使用 Gridster 将这些小部件动态加载到 <li>

我的基本直觉是 ngRepeat 那些 <li>s 但 Controller 不能从范围变量动态加载。 我看到了各种建议in this question 但由于以下原因,我无法将它们放入我自己的代码中:

  1. 我使用的控制器不在主控制器内部,这些控制器可能在不同的地方使用
  2. 小部件是根据用户请求动态创建的。当然,我不会让用户选择要使用的 html/class/controller,这些是预定义的,但他可能会使用一些小部件,也可能不会。

也许其中一个建议对我有用,但我看不到它,因此将不胜感激。以下是相关代码:

HTML:

<div class="widgets-background" ng-controller="Investigation2Ctrl" data-ng-init="refetchData();toggleCollapse();initWidgets();">
    <div id="widgets" class="gridster">
        <ul>
            <li data-row="1" data-col="1" data-sizex="1" data-sizey="1" class="yellow" name="Updates Widget">
                <p style="white-space: pre;">{{gridsterUpdates}}</p>
            </li>
            <li ng-repeat="widget in widgetsList" name="widget.name" data-row="1" data-col="2" data-sizex="1" data-sizey="1">
                <div ng-class="widget.widgetClass" ng-include="widget.widgetHtmlInclude" ng-controller="widget.widgetController"></div>
            </li>
        </ul>
    </div>
</div>

JavaScript:

function Investigation2Ctrl($scope, $http, $dialog, DialogService, Config, ApplicationContextService, CaseHierarchyService, GeoService, Logger, $timeout) {

    $scope.widgetsList = [];
    $scope.initWidgets = function() {
        $scope.addWidget('Export Widget', 'partials/investigation/widgets/widget-export.html');
        $scope.addWidget('Timeline Widget', 'partials/investigation/widgets/widget-timeline.html');
        $scope.addWidget('Search Widget', 'partials/investigation/widgets/widget-search.html');
        $scope.addWidget('Facets  Widget', 'partials/investigation/widgets/widget-facets.html', 'FacetsCtrl');
    };

    $scope.addWidget = function(widgetName, widgetIncludeHtml, widgetController, widgetClass) {
        widgetClass = typeof widgetClass !== 'undefined' ? widgetClass : 'widget-container';
        $scope.widgetsList.push({
            'widgetName': widgetName || '',
            'widgetIncludeHtml': widgetIncludeHtml || '',
            'widgetController': widgetController || '',
            'widgetClass': widgetClass || ''
        });
    };
}

显然我得到的错误是widget.widgetController is undefined,因为他试图加载一个名为widget.widgetController的控制器

我想到的唯一选择是在 JavaScript 中动态创建 &lt;li&gt;&lt;div ng-include... html 并注入它,但是,它很糟糕。

【问题讨论】:

    标签: javascript html angularjs controller widget


    【解决方案1】:

    创建一个虚拟的空函数并将其用作控制器。

    function dummyCtrl() {} // register as controller if required.
    
    widgetController: widgetController ||'dummyCtrl'
    

    【讨论】:

    • 你能解释一下为什么这是有效的,以及关于我的代码的确切位置吗?您是否正在尝试解决不需要控制器的场景?由于那不是问题,所以 ng-controller = ' ' 很好..
    • 你可以为此创建一个 plunker/fiddle 吗?
    猜你喜欢
    • 2018-12-18
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    • 2013-07-14
    • 1970-01-01
    • 2014-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多