如果 Angular 中没有声明模块,则函数未定义

function is undefined if no module is declared in Angular

我是Angular的新手,正在研究控制器。在我的代码中,我设置了一个简单的控制器访问权限,但是当我尝试在浏览器中 运行 时,我遇到了一系列如下所示的错误消息:

"Error: [ng:areq] Argument 'personController' is not a function, got undefined

在我的文件中有这样的内容:

 <h1>CONTROLLER</h1>
 <div class="row" ng-app="" ng-controller="personController">

    <div class="col-sm-6">

        <div class="form-group">
            <label class="col-md-3">First Name: </label>
            <input type="text" class="form-control" ng-model="firstname" />
        </div>

        <div class="form-group">
            <label class="col-md-3">Last Name: </label>
            <input type="text" class="form-control" ng-model="lastname" />
        </div>

        <div class="form-group">
            <p>Full Name: {{ firstname + ', ' + lastname }}
        </div>

    </div>

</div>
<script type="text/javascript">

    function personController($scope) {
        $scope.firstname = 'Jerielle';
        $scope.lastname = 'Doe';
    }

</script>

但是当我尝试声明一个模块时它起作用了:

 <h1>CONTROLLER</h1>
 <div class="row" ng-app="myApp" ng-controller="personController">

    <div class="col-sm-6">

        <div class="form-group">
            <label class="col-md-3">First Name: </label>
            <input type="text" class="form-control" ng-model="firstname" />
        </div>

        <div class="form-group">
            <label class="col-md-3">Last Name: </label>
            <input type="text" class="form-control" ng-model="lastname" />
        </div>

        <div class="form-group">
            <p>Full Name: {{ firstname + ', ' + lastname }}
        </div>

    </div>

</div>
<script type="text/javascript">

    var myApp = angular.module('myApp',[]);

    myApp.controller('personController', function($scope) {
        $scope.firstname = 'Jerielle';
        $scope.lastname = 'Doe';
    });

</script>

我正在学习 w3schools 中的教程。

我的问题是我可以创建一个控制器 w/o 先创建模块吗?

您确实需要创建一个应用程序。对于任何 angular 组件(控制器、指令、服务等)都是如此。这是因为当你使用一个控制器时,angular不仅仅是绑定一个函数,还有一些额外的特性被添加到你的函数中(类似于继承),这些特性将你的控制器添加到消化循环、作用域、等等

你用的第一个就是controller的全局函数声明,你把controller声明为函数。要分析 Angular 函数应该被视为 controller 我们需要使用 post-fix as Controller.

它不起作用的原因是您使用的是 Angular 1.3 + 版本,其中默认禁用全局函数声明。无论您需要做什么,只需使用 angular.module 创建一个模块,然后将组件附加到它。

为了让代码正常工作,您需要在 angular 配置阶段启用设置

app.config(['$controllerProvider',
  function($controllerProvider) {
    $controllerProvider.allowGlobals();
  }
]);

注意

Though you can enable this global declaration function using above setting to make your 1st code working, I'd not prefer to do this. Use angular.module to make your code good as area base.

这是 解释

使用这种方法,即使在缩小之后也更好

  var myApp = angular.module('App',[]);

  myApp.controller('parentController',parentController);

   parentController.$inject = ["$scope"] // inject dependencies 

    function parentController($scope) {

    .....
   }

控制器是模块的一部分。基本上,模块就是 'creates' 你的应用程序,控制器执行你希望它执行的命令,以便你的应用程序成为你想要的样子。将其与人体进行比较。模块是躯干,而控制器是手臂。你不能拥有一个有手臂但没有躯干的正常人体。