如何从指令的字符串动态包含控制器?

时间:2015-02-19 10:05:16

标签: angularjs angularjs-directive angularjs-controller

我需要根据组件名称动态选择ngRepeat中的控制器作为字符串。 Plunker:http://plnkr.co/edit/osLLf0c4eNCpNokyyXCI?p=preview

正如你所看到的,我找到了一个解决方案,但我不认为这是一种Angular方式,因为我已经创建了一堆控制器并将它们分配给"控制器"角度范围之外的变量。

这是HTML:

<table border="1" class="item" data-ng-repeat="component in components">
    <tr>
        <td>
            <div component="component"></div>
        </td>
    </tr>
</table>

的Javascript

var app = angular.module("sortableApp", []);
app.controller("appCtrl", ["$scope", function($scope) {
    $scope.components = [{
        name: 'simpleText',
        tpl: 'simple-text.html',
        content: 'Simple text'
    }, {
        name: 'heading',
        tpl: 'heading.html',
        content: 'Heading'
    }];
}]);
app.directive("component", ["$templateCache", "$compile", function($templateCache, $compile) {
    return {
        restrict: "A",
        scope: {
            component: "="
        },
        controller: function($scope) {
            if(controllers[$scope.component.name]) {
                return controllers[$scope.component.name]($scope);
            }
        },
        link: function(scope, element, attrs) {},
        template: '<div ng-include="component.tpl"></div>'
    }
}]);

var controllers = {
    simpleText: function($scope) {
        $scope.add = function() {
            alert('add text');
        }
    },
    heading: function($scope) {
        $scope.add = function() {
            alert('add heading');
        }
    }
}

如何以棱角分明的方式实现我的目标?谢谢你的回答!

0 个答案:

没有答案