Reputation: 1190
HTML:
<div ng-controller="MainCtrl as ctrl">
<input type="text" ng-model="ctrl.number">
<h2>{{ctrl.number}}</h2>
<button ng-click="ctrl.factorial(ctrl.number)">
Click
</button>
</div>
JS:
angular
.module('myApp', [])
.controller('MainCtrl', MainCtrl)
function MainCtrl() {
var ctrl = this;
ctrl.number = 5;
ctrl.factorial = function(num) {
if (num === 1) {
return 1;
} else {
return num * ctrl.factorial(num-1)
}
} // factorial
}
The number is just staying the way it is, its factorial not being shown. How do I fix this? I'm really lost.
Upvotes: 0
Views: 30
Reputation: 16068
When you pass ctrl.number to the function, its a number so its value is copied. In the function you calculate with recursion the corresponding factorial, but you are just returning it and not changing ctrl.number, which is what you really want.
Easy fix would be to change ng-click="ctrl.factorial(ctrl.number)
to
ng-click="ctrl.number = ctrl.factorial(ctrl.number)
Upvotes: 1