首页 > 解决方案 > 如何使指令使用指令属性中指定的控制器?

问题描述

所以我有一个指令:

<directive data="user" templateUrl="./user.html" controller="UserController"></directive>

如上所示,我希望该指令使用“控制器”属性中指定的控制器。

AngularJS指令可以吗?或者我应该用其他方式,也许用组件?

我的代码目前如下所示:

app.directive('directive', function() {
        
        var controllerName = "UserController"; // i want that to dynamicaly come from attribute
        
        // check if controller extists:
        var services = [];
        app['_invokeQueue'].forEach(function(value){ 
            services[value[2][0]] = true;
        });         
        if (!services[controllerName]) controllerName = false;
        
        return {
            
            scope: { 'data' : '=' },

            link: function (scope) {
                
                Object.assign(scope, scope.data);
            },
            
            templateUrl: function(element, attr) {
                
                return attr.templateurl;
            },
            
            controller: controllerName
            
        }
        
    });

标签: angularjsangularjs-directiveangularjs-controller

解决方案


您可以执行以下操作(不完全按照您的要求 - 它创建了一堆嵌套范围,但应该足够了):

    .directive('directive', () => {
        scope: { 'data' : '=' },
        template: (elem, attrs) => {
          return '<div ng-controller="' + attrs.controller + ' as vm"><div ng-include="' + attrs.template + '"></div></div>';
        }
    });

<directive data="user" templateUrl="./user.html" controller="UserController"></directive>
  • 你可以直接使用 $templateCache 而不是 ng-include
  • 如果你需要控制器/模板/... 是动态的,你需要观察/观察 + dom 操作 + 重新编译东西

推荐阅读