【问题标题】:AngularJS directive can't find required controllerAngularJS 指令找不到所需的控制器
【发布时间】:2018-10-18 15:21:42
【问题描述】:

要点是,在下面的代码中,我需要“modalDirective”来访问要创建的元素列表,该列表位于“modalController”中。我还需要“modalDirective”来创建一个 HTML 元素,该元素使用 ng-model 绑定到“modalController”中的作用域变量,所以如果有其他方法可以做这些事情,我完全愿意接受。

我使用以下参数打开一个模式:

var modalOptions = {
    templateUrl: 'targetUrl/modalPage.html',
    controller: 'modalController'
}
ModalDialogFactory.openModal(modalOptions);

ModalDialogFactory 真的只是打开了模态:

angular.module('myApp')
.factory('ModalDialogFactory', ['$modal', '$rootScope', function ($modal, $rootScope) {
    var modalDialogDefaults = {
        backdrop: 'static',
        keyboard: false,
        scope: $rootScope.$new()
    };
    var modalInstance;
    return {
        showModal: function (modalOptions) {
            var modalConfig = {};
            angular.extend(modalConfig, modalDialogDefaults, modalOptions);
            modalInstance = $modal.open(modalConfig);
            return modalInstance.result;
        },
        closeModal: function (selectedObjs) {
            if (modalInstance != null) {
                modalInstance.close(selectedObjs);
            }
        }
    };

}]);

模式打开,控制器工作正常。到现在为止还挺好。现在,在目标页面中我想使用一个指令:

angular.module('myApp').directive('modalDirective', function ($q, $http, $compile) {
return {
    restrict: 'EAC',
    compile: function(element, attr) {
              return function(scope, element, attr) {
              // Dynamically create new HTML elements   
    }
};
});

然后在modalPage.html中,我引用了modal指令:

<div modal-directive></div>

这也有效,该指令按预期创建动态 HTML 元素。当我想将其中一个元素绑定到“modalController”内的范围变量时,问题就出现了。该指令似乎无法访问控制器,我认为这是某种范围界定问题,但我不确定我哪里出错了。我尝试将此行添加到“modalDirective”:

require: '^^modalController',

但是当我尝试请求控制器时,我得到一个错误:

Error: [$compile:ctreq] Controller 'modalController', required by directive 'modalDirective', can't be found!

有人知道我哪里出错了吗?

【问题讨论】:

  • ModalDialogFactory.openModal()中模态是如何创建的?能否提供更多代码?
  • @Sharko 我在编辑中包含了工厂,所以你现在应该在上面的问题中看到它。

标签: angularjs angularjs-directive angularjs-controller


【解决方案1】:

(假设,使用 uibModal 或其他允许解析的 $modal)

我知道聚会迟到了,但在浏览一些较旧的任务时遇到了这个问题。您需要的问题是 $modal 服务将模式条目添加到控制器范围之外的 HTML(除非控制器是整个页面,这似乎不太可能)。

您可能希望利用 $modal 配置的 resolve 属性,而不是期望传递范围。所以你会做这样的事情:

  • 创建将属性传递给解析属性的模式选项
  • 做你的模态东西
  • 通过您已经在执行的 $modalInstance.close() 返回任何更新

最终会是这样的:

ModalDialogFactory.showModal({
    resolve: {
        listOfStuff: function() { return $scope.list; }
    }
});

这将使您可以在指令中使用 scope.listOfStuff。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多