3

I started learning AngularJs so I started off this way by creating a view, service file and controller file separately as shown below:

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

This is my service file --- ServicesTut.js"

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

});

This is my controller file --- ControllerTut.js

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

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

On launching the code on my browser I get the following error message:

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

Please assist me!

1 Answer 1

4

In your ServicesTut.js you should be using CalculatorService variable instead of app, which is why service doesn't get registered in the CalculatorService module.

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

should be

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

And in controller same thing repeated again, use myApp instead of app while registering controller.

var myApp = angular.module('myApp', ['CalculatorService']);
myApp.controller('CalculatorController', function ($scope, Calculator) {
Sign up to request clarification or add additional context in comments.

2 Comments

You are awesome. Question answered! Also in addition to that I updated my controller file from app.controller..... to myApp.controller. Thanks
@JerryGreen Glad to help you.Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.