0

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.

1
  • You are not consumig the value returned by function Commented May 14, 2016 at 0:45

1 Answer 1

1

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)

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

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.