Show factorial result with AngularJS

0

I'm starting to learn with AngularJS. In a simple function, I need to do the factorial of a number using AngularJS, but I can not 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><bodyng-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>
    
asked by anonymous 13.05.2016 / 04:34

1 answer

1

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

See:

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

MAS!

Be careful when using this type of application because at each interaction with this function, Angular will run a $digest , roughly speaking it will check all the application for change in its properties to check if it is necessary to update or not , making your application a very big performance impact.

What do I recommend doing?

  • Use ng-blur , so the value only refreshes when the user 'exits' the input. Less dynamic option.

  • Use ng-model-options , so you have control over when to rotate the function. For example, if I am going to type the number 15.987, you only need to display the result after I finish typing, so we use the debounce property to run the function x seconds after the user finishes interacting with input .

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

Option1:

<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: link

Option 2:

Just change your input to:

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

Example: link

    
13.05.2016 / 14:06