Show factorial output with Angularjs

Asked

Viewed 255 times

0

I’m starting to learn from Angularjs. In a simple function, I need to make the factorial of a number using Angularjs, but I cannot return the result on the screen (HTML page). Could someone help me?

<!DOCTYPE html>
<html ng-app="fatorialApp">

<head>
  <meta charset="UTF-8" />
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
</head>

<body ng-controller="fatorialController">

  <div>
    <label>Número:</label>
    <input type="text" ng-model="numero" placeholder="Calcular o fatorial">
    <hr>
    <h1>{{ resultado }}</h1>
  </div>

  <script>
    var app = angular.module('fatorialApp', []);
    app.controller('fatorialController', function($scope) {
      $scope.resultado = function() {

        var resultadoDoFatorial = 1;
        for (var i = 1; i <= $scope.numero; i++) {
          resultadoDoFatorial = resultadoDoFatorial * i;
        }
        return resultadoDoFatorial;
      }
    });
  </script>
</body>

</html>

1 answer

1


Very simple! How are you referencing in your h1 directly a function, just put so in your html {{ resultado() }} ready, it will work.

Behold:

<input type="text" ng-model="numero" placeholder="Calcular o fatorial" />
<h1>{{ resultado() }}</h1>

BUT!

Be careful when using this type of application because every interaction with this function the Angular will run a $digest, roughly speaking it will check all the request for change in its properties to verify whether it is necessary to update or not, making your application can have a very large impact on performance.

What I recommend to do?

  • Utilise ng-blur, so the value only updates when the input 'quit' user. Less dynamic option.

  • Utilise ng-model-options, so you have control of when to run the function. For example, if I’m going to type the number 15,987, you only need to display the result after I finish typing, then we use the property debounce to run the function x seconds after the user has finished interacting with the input.

See the two examples below and decide which one best applies to your scenario.

Option 1:

<input type="text" ng-model="numero" placeholder="Calcular o fatorial" ng-blur="rodaResultado()">
<h1>{{ resultado }}</h1>


$scope.rodaResultado = function() {
    var resultadoDoFatorial = 1;
    for (var i = 1; i <= $scope.numero; i++) {
        resultadoDoFatorial = resultadoDoFatorial * i;
    }
    $scope.resultado = resultadoDoFatorial;
}

Example: http://plnkr.co/edit/9vFoYSAHhdZIXdcjuIuF?p=preview


Option 2:

Just change your input for:

<input type="text" ng-model="numero" placeholder="Calcular o fatorial" ng-model-options="{ debounce: 800}">

Example: http://plnkr.co/edit/D8uAxr?p=preview

Browser other questions tagged

You are not signed in. Login or sign up in order to post.