【问题标题】:Error: [ng:areq] Argument 'Controller' is not a function, got undefined错误:[ng:areq] 参数“控制器”不是函数,未定义
【发布时间】:2014-11-10 02:30:14
【问题描述】:

在为对话框实现模式时,我得到了Error: [ng:areq] Argument 'ModalInstanceCtrl' is not a function, got undefined。我在同一个 .js 文件中有两个控制器。错误显示第二个控制器的名称。

ng-app 包含在主 html 文件中。

<div ng-app = "LoginApp">
  <div ng-view>
    <!-- partial will go here -->
  </div>
</div>

角度路线

var LoginApp = angular.module('LoginApp', ['ngResource', 'ngRoute', 'ui.bootstrap'])
LoginApp.config(function($routeProvider, $locationProvider) {
  $routeProvider
    .when('/', {controller: LoginCtrl, templateUrl: '/js/templates/login.html'})
    .otherwise({redirectTo: '/'})
    $locationProvider.html5Mode({
      enabled: true,
      requireBase: false
    });
})

LoginCtrl.js 文件

'use strict'

var LoginCtrl = ['$scope', '$modal', '$log', function($scope, $modal, $log) {
  $scope.authenticate = function(){

    var loginModal = $modal.open({
      templateUrl: 'login-modal.html',
      controller: 'ModalInstanceCtrl',
      resolve: {
        modalData: function () {
          return {
              user: {
                  name: '',
                  password: ''
              }
          };
        }
      }
    });

    loginModal.result.then(function (user) {
      $log.info("My name is:" + user.name);
    }, function () {
        $log.info('Modal dismissed at: ' + new Date());
    });
  }
}];

var ModalInstanceCtrl = ['$scope', '$modalInstance', 'modalData', function($scope, $modalInstance, modalData){

}];

LoginCtrl.js 文件中,LoginCtrl 不会显示此错误,但ModalInstanceCtrl 的声明未定义。谁能告诉我为什么会这样。

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    $modal.open()的参数中,改成这样:

    ...
    controller: 'ModalInstanceCtrl',
    ...
    

    对此:

    ...
    controller: ModalInstanceCtrl,
    ...
    

    注意,控制器的名称没有引号,因为您希望 AngularJS 使用 ModalInstanceCtrl 变量,而不是使用 angular 注册的控制器。

    或者,如果您想保留引号,您可以使用 AngularJS 注册 ModalInstanceCtrl,如下所示:

    LoginApp.controller('ModalInstanceCtrl',  ['$scope', '$modalInstance', 'modalData', function($scope, $modalInstance, modalData){
      ...
    }]);
    

    任何一种方式都可以。

    【讨论】:

    • 我尝试了用 angular 注册控制器的替代方法,然后使用带有引号 'ModalInstanceController' 的控制器名称,但它会引发相同的错误。但是第一种方法确实有效。感谢您对此的清晰看法。
    • LoginApp.controller('ModalInstanceCtrl', ['$scope', '$modalInstance', 'modalData', function($scope, $modalInstance, modalData){ }]);这就是我用于控制器向我的角度模块注册的内容。它现在可以使用引号。
    • 哦,是的,你说得对,你需要注册一个模块,我脑子里放了个屁。让我更新答案以造福未来的读者。
    • 当您将.when 像这样.config {..... }.when ('/' ....) 放在配置之外时,也会发生此ngareq 错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    • 2015-11-03
    • 2016-10-23
    • 2015-10-10
    • 2016-11-12
    • 2016-03-04
    • 2015-11-18
    相关资源
    最近更新 更多