AngularJs:Argument不是一个未定义的函数

时间:2015-09-08 15:50:44

标签: javascript angularjs html5 angularjs-service angularjs-controller

我开始学习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&#34;

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

请帮助我!

1 个答案:

答案 0 :(得分:4)

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) {