Reputation: 363
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();
}]);
Upvotes: 1
Views: 345
Reputation: 61
This should work:
angular
.module('app', [])
.factory('Calculator', function () {
return function () {
return Math.random();
}
});`
Upvotes: 0
Reputation: 19748
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>
Upvotes: 0
Reputation: 32327
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.
Upvotes: 2