angularjsangularjs-ng-repeatng-controllerangular-ui-bootstrap-tab

Is there any way to assign ng-controller dynamically when iterate over an collection of objects?


Using angular 1.6.6 and ui-bootstrap 2.5.0

I'm trying to use a controller if the action property value is not null.

The logic for each of my tabs is very different so that I don't want to put all tabs in a single controller. Is there any way for this problem?

Actions

$scope.actions = [
    {
        slug: "basicData",
        title: "Grunddata",
        icon: "fa fa-table",
        template: templatePath + "basicData.html",
        disabled: false,
        controller: null
    }, {
        slug: "responsible",
        title: "Ansvariga",
        icon: "fa fa-address-book-o",
        template: templatePath + "responsible.html",
        disabled: false,
        controller: null
    }, {
        slug: "reportTime",
        title: "Rapportera tid",
        icon: "fa fa-clock-o",
        template: templatePath + "reportTime.html",
        disabled: false,
        controller: "ActivityTimeReportingController"
    }

];

Here's my tabset

<uib-tabset active="activePill" vertical="true" type="pills">
            <uib-tab ng-repeat="action in actions" index="$index+1" disable="action.disabled">
                <uib-tab-heading>
                    <span class='{{action.icon}}'></span>&nbsp;{{action.title}}
                </uib-tab-heading>
                <div ng-include="action.template" ng-if="!action.controller" ng-controller="action.controller"></div>
                <div ng-include="action.template" ng-if="action.controller"></div>
            </uib-tab>
        </uib-tabset>

I get the following error

The controller with the name 'action.controller' is not registered.

Curly brackets does not make any difference.

I have tried using a function aswell:

    $scope.getController = function (controllerName) {
    return controllerName.ToString();
};

And in my tabset:

<div ng-include="action.template" ng-if="!action.controller" ng-controller="getController(action.controller)"></div>

With the same error message

The controller with the name 'getController(action.controller' is not registered.

Is there any way to assign ng-controller dynamically when iterate over an collection of objects?


Solution

  • Create dynamic directives then specify a controller for each, pretty much instead of using ng-include roll your own dynamic directive with binding for template url

    http://www.codelord.net/2015/05/19/angularjs-dynamically-loading-directives/

    If you dont have too many types of actions.. then use ng-if or ng-switch and create a line for each action with ng-controller or your directive that uses a controller. Dynamic code that you're trying to achieve isn't the right way to do it, imo.