AngularJs: 参数不是未定义的函数

AngularJs: Argument is not a function got undefined

我开始学习 AngularJs 所以我通过分别创建视图、服务文件和控制器文件开始了这种方式,如下所示:

<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="ServicesTut.js"></script> 
<script src="ControllerTut.js"></script>   
</head>

<body>
<div class="container">

            <div ng-controller="CalculatorController">
                Enter a number:
                <input type="number" ng-model="number">
                <button  ng-click="findSquare()">Square</button>
                <div>{{answer}}</div>
            </div>

    </div>
</body>
</html>

这是我的服务文件 --- ServicesTut.js"

var CalculatorService = angular.module('CalculatorService', [])
app.service('Calculator', function () {
    this.square = function (a) { return a*a};

});

这是我的控制器文件--- ControllerTut.js

var myApp = angular.module('myApp', ['CalculatorService']);
app.controller('CalculatorController', function ($scope, Calculator) {

    $scope.findSquare = function () {
        $scope.answer = Calculator.square($scope.number);
    }
});

在我的浏览器上启动代码时,我收到以下错误消息:

Error: Argument 'CalculatorController' is not a function, got undefined

请帮助我!

在您的 ServicesTut.js 中,您应该使用 CalculatorService 变量而不是 app,这就是服务未在 CalculatorService 模块中注册的原因。

var CalculatorService = angular.module('CalculatorService', [])
app.service('Calculator', function () {

应该是

var CalculatorService = angular.module('CalculatorService', [])
CalculatorService.service('Calculator', function () {

并且在控制器中再次重复同样的事情,在注册控制器时使用 myApp 而不是 app

var myApp = angular.module('myApp', ['CalculatorService']);
myApp.controller('CalculatorController', function ($scope, Calculator) {