1

I'm trying to get a service instance but am getting an error. I am getting the exception that Calculator.random() is not a function. Any idea what I'm doing wrong?

angular
    .module('app')
    .factory('Calculator',function(){
        var random = {};
        random.number = function (){
            return Math.random();
        };
        return random;
    });

angular
    .module('app')
    .controller('homeCtrl', ['$scope','Calculator', function ($scope,Calculator) {

        $scope.random = Calculator.random();

    }]);

3 Answers 3

2

You can try like this:

angular
.module('app').controller('homeCtrl', function($scope, Calculator) {
$scope.random=Calculator.number();//in your factory number holds the random function.
}

IN your case its breaking reason: Calculator.random(); is not a function.

Sign up to request clarification or add additional context in comments.

Comments

0

Like Cyril said, you define an object with a local name random in the calculator factory definition. You then return that object but that object has a property called number that points to a function not a property called random.

angular
    .module('app', [])
    .factory('Calculator',function(){
        var random = {};
        random.number = function (){
            return Math.random();
        };
        return random;
    });

angular
    .module('app')
    .controller('homeCtrl', ['$scope','Calculator', function ($scope,Calculator) {

        $scope.random = Calculator.number();

    }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app">
<div ng-controller="homeCtrl">{{random}}</div>
</div>

Comments

0

This should work:

angular
    .module('app', [])
    .factory('Calculator', function () {
        return function () {
            return Math.random();
        }
    });`

Comments

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.