Search code examples
javascriptangularjsconditional-statementsangularjs-rootscopeangular2-databinding

AngularJS: Applying a function to 2-way data binding with a reroll button (reloadRoute??)


AngularJS APP

I would like to understand how I can solve this issue of the infinite digest Loop, should I write a conditional?

The objective is to use angular's 2-way data binding, but I need to modify the output to sort the letters randomly.

My HTML:

                <div class="container-fluid phrase-container text-center">
                <!-- == User Phrase Input == -->
                <input type = "text" ng-model = "phrase.firstPhrase" placeholder="Please enter phrase"><br><br>
            </div>

                <div class="container-fluid anagram-container text-center">
                <!-- == Final anagram ==  -->
                Anagram: {{phrase.fullAnagram()}}
            </div>

My javascript:

   var app = angular.module("app", []);

   app.controller('mainController', function($scope) {
   $scope.main = {};
   $scope.main.title = "AnagramJS";

// Refresh Page acts as reroll button
$scope.reloadRoute = function() {
    $route.reload();
};

// Anagram Creation
$scope.phrase = {
    firstPhrase: "",
    fullAnagram: function() {
        var finalPhrase;
        finalPhrase = this.firstPhrase.split('').sort(function() {
            return 0.5 - Math.random()
        }).join('');

        return finalPhrase

    }
};
   });

Solution

  • Simple $watch on scope model seems to work fine, so you could use:

    <input ng-model="word" type="text"/>
    <p>
       {{anagram}}
    </p>
    

    And in js:

    $scope.$watch('word', (newVal, oldVal) => {
    if (newVal) {
      // set anagram to randomize
      $scope.anagram = newVal.split('').sort(function() {
        return 0.5 - Math.random()
      }).join('');
    } else {
      // empty anagram if word is empty
      $scope.anagram = "";
    }
    });
    

    You can check how it works in this fiddle: https://fiddle.jshell.net/pegla/kemrr0ka/4/

    UPDATE:

    There's no need to use routing for reroll button, you can simply create function and call it multiple times, I added one way of doing it in my latest fiddle:

    https://fiddle.jshell.net/kemrr0ka/5/